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.
Solution:Code:
<span style="font-size:14px;">class Solution {
public:
string getPermutation(int n, int k) {
vector<int> nums(n, 1);
int t = 1;
for (int i = 2; i <= n; ++i) {
nums[i-1] = i;
t *= i;
}
t /= n;
--k;
string result;
while (n > 1) {
int q = k/t;
k = k%t;
--n;
t = t/n;
result += '0'+nums[q];
nums.erase(nums.begin()+q);
}
result += '0'+nums[0];
return result;
}
};</span>