leetcode 60. Permutation Sequence(康托展开)

描述:

  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==1 ){
            result="1";
            return result;
        }
            
        //generate nums
        for( int i=0;i<n;i++ )
            nums.push_back(i+1);
        //calculate factorial times,fac[0]=(n-1)!,fac[1]=(n-2)!
        for( int i=n-1;i>=0;i-- ){
            if( i==n-1 )
                fac.push_back(1);
            else            
                fac.insert(fac.begin(),(n-i-1)*(*fac.begin()));
        }
        //calculate every place from high
        next_k=k;
        for( int i=0;i<n-1;i++ ){
            now_seq=(next_k-1)/fac[i]+1;
            temp.push_back(nums[now_seq-1]);
            nums.erase(nums.begin()+now_seq-1);
            next_k=(next_k-1)%fac[i]+1;
        }
        temp.push_back(nums[0]);
        //into string
        for( int i=0;i<n;i++ ){
            result.append(1,'0'+temp[i]);
        }
        return result;
    }
};
posted @ 2016-02-26 20:59  Lucio.Yang  阅读(238)  评论(0编辑  收藏  举报