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 getPermutation(int n, int k) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int count=0;
int *A=new int[n];
for(int i=0 ; i<n ; i++)
A[i]=i+1;
vector<string> str(k);
_permutations(A,n,0,count,k,str);
return str[k-1];
}
void _permutations(int A[] , int n , int depth , int& count , int k, vector<string>& str){
if(depth==n-1){
string temp = convert(A,n);
if(count<k){
str[count]=temp;
count++;
if(count==k)
sort(str.begin(),str.end());
}
else
Insert(str,temp);
}
for(int i=depth ; i<n ; i++){
swap(A[depth],A[i]);
_permutations(A,n,depth+1,count,k,str);
swap(A[depth],A[i]);
}
}
string convert(int A[] , int n){
string ret(n,'\0');
for(int i=0 ; i<n ;i++){
ret[i]='0'+A[i];
}
return ret;
}
void Insert(vector<string>& pstr , string str){
int count=pstr.size()-1;
if(str>pstr[count])
return ;
pstr[count]=str;
for(int i=count-1 ; i>=0 ; i--){
if(pstr[i]>str)
swap(pstr[i],pstr[i+1]);
}
return ;
}
};看一看神一样的代码:
class Solution {
public:
string getPermutation(int n, int k) {
string str;
vector<int> factorial(n + 1, 1);
for (int i = 1; i <= n; ++i) {
str += i + '0';
factorial[i] = factorial[i-1] * i;
}
string perm;
--k; // convert to 0-based index
for (int i = n - 1; i >= 0; --i) {
int quotient = k / factorial[i];
perm += str[quotient];
str.erase(quotient, 1);
k %= factorial[i];
}
return perm;
}
};
本文介绍了一种算法,用于找出由1到n整数构成的所有排列中的第k个排列序列。通过递归或数学组合的方法,高效地解决了这一问题,并提供了两种实现方案。
219

被折叠的 条评论
为什么被折叠?



