[LeetCode] 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.

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

 

Hide Tags
 Backtracking Math
 
 

    这道题可以直接穷举然后数第k 个,或者 迭代k次得到返回值,或者直接计算出结果。我用是直接计算结果,很多细节上需要处理。
 
#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
    string getPermutation(int n, int k) {
        if(n <2)    return "1";
        int tab[10]={1};
        for(int i =1;i<=9;i++)
            tab[i] = tab[i-1]*i;
        int remain[9]={0};
        for(int i=0;i<9;i++)
            remain[i]=i+1;
        int cnt = n;
        string ret = "";
        while(cnt>0){
            cnt--;
            int num = (k-1)/tab[cnt];
//            cout<<"num="<<num<<endl;
            int idx = 0;
            while(remain[idx]==0)   idx++;
            for(int i=0;i<num;i++)
                if(remain[++idx]==0)  i--;
//            cout<<"idx="<<idx<<endl;
            ret += '0'+remain[idx];
            remain[idx]=0;
            k = k - num*tab[cnt];
//            cout<<endl;
        }
        return ret;
    }
};

int main()
{
    Solution sol;
    cout<<sol.getPermutation(9,213)<<endl;
    return 0;
}

 

 
 
posted @ 2015-03-28 04:09  A_zhu  阅读(264)  评论(0编辑  收藏  举报