原题:
解决方法:
代码:
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.
比较巧妙的一道题。
根据排列的特性,我们知道在n位上一个数字出现的次数是(n-1)!次。根据这个特性,我们从高位开始取数字,知道所有的数字被取出。
代码:
string getPermutation(int n, int k) {
string num = "123456789", res = "";
vector<int> func(n, 1);
for(int i = 1; i < n;i++){
func[i] = func[i-1] * i;
}
--k;
for(int i=n;i > 0; i--){
int index = k/func[i-1];
k %= func[i-1];
res += num[index];
num.erase(index, 1);
}
return res;
}