您的位置:首页 > 产品设计 > UI/UE

leetcode No60. Permutation Sequence

2016-08-01 11:28 309 查看


Question:

The set
[1,2,3,…,n]
contains a total of n!
unique permutations.

By listing and labeling all of the permutations in order,

We get the following sequence (ie, for n = 3):

"123"

"132"

"213"

"231"

"312"

"321"


Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

Algorithm:
用一个数组v,存储1到n,先算最高位,最高位在v中下标,index=(k-1)/((n-1)!)
确定最高位以后,要把v中该元素删除,还要更新k的值,k-=index*(n-1)!
Accepted Code:
class Solution {  //最高位等于k/(factorial(n-i))-1
public:
string getPermutation(int n, int k) {
vector<int> v(n);   //在v中选元素,最高位选定后,删除
vector<int>::iterator it=v.begin();
for(int i=0;i<n;i++)
v[i]=i+1;
string res;
while(n)
{
it=v.begin();
int index=(k-1)/factorial(n-1);
res.push_back(v[index]+'0');
k-=index*factorial(n-1);
v.erase(it+index);
n--;
}
return res;
}
int factorial(int n)  //求阶乘
{
int res=1;
if(n<2)return res;
while(n)
{
res*=n;
n--;
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: