Permutation Sequence
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.
1 class Solution {
2 public:
3 // case n = 3, k = 2 (k starts from 1)
4 string getPermutation(int n, int k) {
5 string s;
6 int total = 1;
7 for(int i = 1; i <= n; i++) {
8 s.push_back(i+'0'); // s="123";
9 total *= i; // total = 1x2x3
10 }
11 k--;
12 string res;
13 while(n) {
14 total /= n;
15 int i = k / total;
16 res.push_back(s[i]);
17 s.erase(i,1);
18 k %= total;
19 n--;
20 }
21 return res;
22 }
23 };

浙公网安备 33010602011771号