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) {
vector<char> pers(n, '1');
int fact = n;
for (int i=1; i<n; i++) {
fact *= i;
pers[i] = '1' + i;
}
k--;
string ans;
for (int i=0; i<n; i++) {
fact /= (n-i);
const int j = k / fact;
k %= fact;
ans.push_back(pers[j]);
pers.erase(pers.begin()+j);
}
return ans;
}
};基本思路:
参照普通进制的方法,求出每位的权重,从高位到低位利用整除和取余求出每位的值。
区别为,此权重都是阶乘值,不像普通进制,为基数的各次幂。
Permutation Sequence -- leetcode
原文地址:http://blog.csdn.net/elton_xiao/article/details/44807001