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

Permutation Sequence

2013-11-14 20:02 513 查看
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.

代码:

string getPermutation(int n, int k) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int fac[10];
fac[0] = 1;
for(int i = 1; i <= 9; i++){
fac[i] = fac[i-1]*i;
}
string result = "";
vector<int> nums;
for(int i = 0; i < n; i++)
nums.push_back(i+1);
for(int i = n; i >= 1; i--){
if(k <= fac[i-1]){
result += (nums[0]+'0');
nums.erase(nums.begin());
}
else if(k == fac[i]){
for(vector<int>::iterator it = nums.end()-1; it >= nums.begin(); it--){
result += (*it+'0');
}
break;
}
else{
int j = (k-1)/fac[i-1]+1;
k = k - (j-1)*fac[i-1];
vector<int>::iterator it = nums.begin();
while(j > 1){
it++;
j--;
}
result += (*it+'0');
nums.erase(it);
}
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: