60. Permutation Sequence

Posted zhuangbijingdeboke

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了60. Permutation Sequence相关的知识,希望对你有一定的参考价值。

 1 class Solution 
 2 {
 3 public:
 4     string res;
 5     vector<int> fact={1,1,2,6,24,120,720,5040,40320,362880};
 6     string getPermutation(int n, int k) 
 7     {
 8         string num;
 9         char dd=n+0;
10         for(char c=1;c<=dd;c++)
11             num.push_back(c);
12         com(num,k,n);
13         return res;
14     }
15     
16     void com(string &num,int &k,int &n)
17     {
18         if(k==fact[n])
19         {
20             reverse(num.begin(),num.end());
21             res=res+num;
22             return;
23         }
24         if(n==1)
25         {
26             res.push_back(num[0]);
27             return;
28         }
29         int f=fact[n-1];
30         n--;
31         int cur=k/f;
32         k=k%f;
33         if(k==0)
34         {
35             res.push_back(num[cur-1]);
36             auto p=num.begin()+(cur-1);
37             num.erase(p);
38             reverse(num.begin(),num.end());
39             res=res+num;
40             return;
41         }
42         else if(k==1)
43         {
44             res.push_back(num[cur]);
45             auto p=num.begin()+cur;
46             num.erase(p);
47             res=res+num;
48             return;
49         }
50         else
51         {
52             res.push_back(num[cur]);
53             auto p=num.begin()+cur;
54             num.erase(p);
55             com(num,k,n);
56         }
57     }
58 };

用的数学方法,把数字排起来,用序列k去除以n-1的阶乘,取结果为下标,在排列好的字符串里面去取数字,同时判定是否可以直接完结程序。

以上是关于60. Permutation Sequence的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode(60):Permutation Sequence

LeetCode31 Next Permutation and LeetCode60 Permutation Sequence

60. Permutation Sequence

60. Permutation Sequence

Permutation Sequence LT60

60. Permutation Sequence