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.
Note: Given n will be between 1 and 9 inclusive.
分析:
坦言,此题好难,规律的总结来自网络!代码根据大婶的规律写的!
原文分析:http://www.cnblogs.com/boring09/p/4253508.html
一个一个模拟肯定要超时,只有生算找规律呗。
比如n=4,k=10,先将n=4的所有排列写出来:
(1) 1 2 3 4 <--第一个序列2 3 4,顺序(2) 1 2 4 3
(3) 1 3 2 4
(4) 1 3 4 2
(5) 1 4 2 3
(6) 1 4 3 2 <--最后个序列4 3 2,逆序
(7) 2 1 3 4
(8) 2 1 4 3
(9) 2 3 1 4
(10) 2 3 4 1 <-- 目标序列
(11) 2 4 1 3
(12) 2 4 3 1
(13) 3 1 2 4
(14) 3 1 4 2
(15) 3 2 1 4
... (省略后面的)
假设k=10最终的结果是ABCD
a)首先确定A。
4!=24,在这4!个组合中,寻找第k=10个的开头A,可以算出A应该是1~n里面的第 ceiling{k / 3!}=1.666=2个(ceiling表示取上整),即A=2。最后把2从1~n中删除,更新k,令k=k%3!=4(在(n-1)!中寻找第4个组合的开头B)
b)然后确定B。
因为k=4 > 2!=2,所以可以算出B应该是1~n里面的第ceiling{k/2!}=2个,因为2之前被删掉了,所以现在第2个数字是3,即B=3。最后把3从1~n中删除,更新k=k%2!=2
c)接着看C。
因为k=0,说明我们要求的序列肯定是某个序列的结尾处,所以之后的数字依次按照从大到小的方式输出即可,即C=4。把4从1~n中删除,继续。
d)最后看D。
因为k=0,同上,可得D=1。
给大婶跪了.........,托大婶的福,上面思路转化为代码:
class Solution {
public:
string getPermutation(int n, int k) {
string result="";
string numstr(n+1,'*');
for(int i=1;i<=n;i++)
numstr[i]=i+'0';
dfs(result,numstr,n,k);
return result;
}
void dfs(string &result,string &numstr,int n,int curk)
{
if(numstr.size()==1)//snumtr[0]=‘*’,是个无用字符
return;
int n1=factorial(n-1);//求阶乘
int kk=ceil(1.0*curk/n1);//向上取余
if(kk==0)
{
//k=0说明我们要求的序列肯定是某个序列的结尾处
//所以之后的数字依次按照从大到小的方式输出即可
sort(numstr.begin(),numstr.end());
for(int i=0;i<numstr.size()-1;i++)
result+=numstr[numstr.size()-i-1];
return;
}
result+=numstr[kk];
numstr.erase(numstr.begin()+kk);//铲除
dfs(result,numstr,n-1,curk%n1);
}
//求正整数n的阶乘
int factorial(int n)
{
int sum = 1;
for(int j = 2; j <= n; j++)
sum *= j;
return sum;
}
};
附暴力办法(超时):
class Solution {
public:
void next_permutation(string& nums) {
if(nums.empty() || nums.size()==1)
return;
string::iterator ite1=nums.end()-1;
for(;;)
{
string::iterator ite2=ite1;
ite1--;
if(*ite1 < *ite2)
{
string::iterator itej=nums.end();
while(!(*ite1 < *--itej));
iter_swap(ite1,itej);
reverse(ite2,nums.end());
return;
}
if(ite1==nums.begin())
{
reverse(nums.begin(),nums.end());
return;
}
}
}
string getPermutation(int n, int k) {
string result(n,'0');
for(int i=1;i<=n;i++)
result[i-1]=i+'0';
for(int i=0;i<k-1;i++)//执行k-1次
next_permutation(result);
return result;
}
};
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/51648717
原作者博客:http://blog.csdn.net/ebowtang
本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895