leetcode 60. Permutation Sequence(康托展开)

时间:2024-08-17 15:05:26

描述:

  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):

    1.   "123"
    2.   "132"
    3.   "213"
    4.   "231"
    5.   "312"
    6.   "321"

  Given n and k, return the kth permutation sequence.

思路:

  参见我的博文:全排列的编码与解码:康托展开

代码:

class Solution {
public:
string getPermutation(int n, int k) {
vector<int> temp;
vector<int> fac;
vector<int> nums; int next_k,now_seq;
string result; if( n== ){
result="";
return result;
} //generate nums
for( int i=;i<n;i++ )
nums.push_back(i+);
//calculate factorial times,fac[0]=(n-1)!,fac[1]=(n-2)!
for( int i=n-;i>=;i-- ){
if( i==n- )
fac.push_back();
else
fac.insert(fac.begin(),(n-i-)*(*fac.begin()));
}
//calculate every place from high
next_k=k;
for( int i=;i<n-;i++ ){
now_seq=(next_k-)/fac[i]+;
temp.push_back(nums[now_seq-]);
nums.erase(nums.begin()+now_seq-);
next_k=(next_k-)%fac[i]+;
}
temp.push_back(nums[]);
//into string
for( int i=;i<n;i++ ){
result.append(,''+temp[i]);
}
return result;
}
};