Permutation Sequence

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

  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.

Solution:

 1 string itoax(int num)
 2 {
 3     stringstream result;
 4 
 5     result<<num;
 6     return result.str();
 7 }
 8 int fac(int n)
 9 {
10     if(1==n || 0==n)
11         return 1;
12     else
13         return n*fac(n-1);
14 }
15 string get_each_char(vector<int> &a,int &k)
16 {
17     int n=a.size();
18     if(1==n) 
19     {
20         string b=itoax(a[0]);
21         a.erase(a.begin(),a.end());
22         return b;
23     }
24     int nn=fac(n-1);
25     int i=ceil(double(k)/nn);
26     string b=itoax(a[i-1]);
27     k=k-nn*(ceil(double(k)/nn)-1);
28     a.erase(a.begin()+i-1,a.begin()+i);    
29     return b;
30 }
31 class Solution {
32 public:
33     string getPermutation(int n, int k) {
34         string result;
35     vector<int> a;
36     for(int i=1;i<=n;i++)
37         a.push_back(i);
38     while(!a.empty())
39     {
40         string c=get_each_char(a,k);
41         result +=c;        
42     }
43     return result;
44         
45     }
46 };

posted on 2015-07-08 22:23  Riden  阅读(123)  评论(0编辑  收藏  举报

导航