您的位置:首页 > 产品设计 > UI/UE

leetcode Permutation Sequence

2016-08-21 18:44 399 查看
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):
"123"

"132"

"213"

"231"

"312"

"321"


Given n and k, return the kth permutation sequence.

开始的思路就是求所有排列组合,按照字符序排序后输出第k个,不出所料,果然超时。。。

搜了别人的思路,有以下理解:

如果最终结果是"a1,a2,a3...an",那么我们要做的就是从第一位n1开始逐个确认n2、n3...直到得到第k个字符串组合

 n个字符(假设如此题中不重复)的排列共有n!个

 以第一个字符a1为例,不管a1,后面的n-1(即a2、a3...an)个字符的所有组合为(n-1)!,那么对于所有字符位于第一个的位置,均对应一个(n-1)!个组合----即n! = n*(n-1)!个组合

 第二个字符a2,如果确定第一个和第二个字符是哪一个,共有(n-2)!个组合----即n! =(A2/n)*(n-2)!个组合,依次类推。

 想要找第K个字符串组合中第一个字符是哪个,就要先计算第K个字符串组合位于哪个字符对应的(n-1)!中,即K/(n-1)!个字符位于组合的第一位,问题规模就缩小为找第(K-[K/(n-1)!] * (n-1)!)个长度为n-1的n-1个字符的组合
 要找第二个就要计算排除确定的第一个字符的n-1个字符集中,第K - [K/(n-1)!] * (n-1)!个组合再哪个字符对应的(n-2)!中。依次类推即可得到最终第K个组合。

代码如下:

</pre></p><p><pre name="code" class="cpp">class Solution {
public:
string getPermutation(int n, int k) {
if(n<=0 || k<=0)
return NULL;
string result;
string s(n,'0');
int i, j, find, fac;
for(i=0;i<n;++i)
s[i] += i+1;
j = n-1;
k--;//题目中k从1开始,此方法是从0开始,故在此减一
while(j>=0)
{
fac = getNFactorial(j);
find = k/fac;
result += s[find];
adjust(s, find,j);
k = k-find*fac;
--j;
}
return result;
}
static int getNFactorial(int n)
{
int result = 1;
for(int i=2;i<=n;++i)
result *= i;
return result;
}
static void adjust(string &s, int find, int n)
{
for(int i=find;i<n;++i)
s[i] = s[i+1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode