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):
"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.
深度暴力果然超时
class Solution {
public:
string dfs(int num[],int m,int n,int &cnt,int k){
if(m>n){
if(++cnt==k){
string str;
for(int i=1;i<=n;i++)
str+=(char)(num[i]+'0');
return str;
}
return "";
}
for(int i=m;i<=n;i++){
swap(num[i],num[m]);
string t=dfs(num,m+1,n,cnt,k);
if(t!="")return t;
swap(num[i],num[m]);
}
return "";
}
string getPermutation(int n, int k) {
int num[10];
for(int i=1;i<=9;i++)num[i]=i;
int cnt=0;
return dfs(num,1,n,cnt,k);
}
};
看来得找规律了,
第一位每个数字开头的序列都有(n-1)!个序列;
第二位每一个数开头都有(n-2)!个序列;依次类推
康托编码:
假设n个不重复元素,第k个排列是a1,a2,a3,a4,a5...an
a1 = k/(n-1)!
k2 = k%(n-1)!
a2 = k2/(n-2)!
........
........
k(n-1) = k(n-2)%2!
a(n-1) = k(n-1)/1!
an = 0
class Solution {
public:
string getPermutation(int n, int k) {
string result;
string s(n,'0');
int i,d(1),q;
for(i=1;i<=n;++i){
s[i-1] += i;
d *= i;
}
--k;//k--因为康托编码从0开始
for(i=n;i>=1;--i){
d = d/i;
q = k/d;
k %=d;
result.push_back(s[q]);
s.erase(s.begin()+q);
}
return result;
}
};