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 for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
考察:阶乘,排列。从例子n=3,我们可以发现1为首位,2为首位,3为首位,固定住首位后,每个首位有2!种选择,此外考虑起始index为1,故可找出每一位的规律;
class Solution {
public:
string getPermutation(int n, int k) {
string res = "";
string s = "123456789";
vector<int> fac(n, 1);
k --;
for (int i = 1; i < n; i ++)
fac[i] = fac[i-1] * i;
for (int i = n; i >= 1; i --) {
int j = k / fac[i-1];
k %= fac[i-1];
res.push_back(s[j]);
s.erase(j, 1);
}
return res;
}
};