leetcode60 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.

 1 class Solution {//找规律,统计,判断每一位的字符
 2 public:
 3     string getPermutation(int n, int k) {
 4         string ans;
 5         vector<char> list;
 6         for(int i=1;i<=n;i++)
 7             list.push_back(i+'0');
 8 
 9         while(k)
10         {
11             if(n==1)
12             {
13                 ans+=list[0];
14                 break;
15             }
16 
17             int j=getj(n-1);
18             int t=k/j;
19             int k2=k-t*j;
20             t=(k2==0?t:t+1);
21 
22             ans+=list[t-1];
23             list.erase(list.begin()+(t-1));
24 
25             n--;
26             if(k2==0)
27                 k=j;
28             else
29                 k=k2;
30 
31         }
32 
33         return ans;
34     }
35 
36     int getj(int n)
37     {
38         int ans=1;
39         for(int i=1;i<=n;i++)
40             ans*=i;
41         return ans;
42     }
43 };
View Code

 

posted @ 2016-01-06 15:43  西小贝  阅读(146)  评论(0编辑  收藏  举报