forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
permutation-sequence.cpp
33 lines (30 loc) · 1.05 KB
/
permutation-sequence.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Time: O(n^2)
// Space: O(n)
class Solution {
public:
string getPermutation(int n, int k) {
vector<int> nums;
int total = 1;
for (int i = 1; i <= n; ++i) {
nums.emplace_back(i);
total *= i;
}
// Cantor Ordering:
// Construct the k-th permutation with a list of n numbers
// Idea: group all permutations according to their first number (so n groups, each of
// (n - 1)! numbers), find the group where the k-th permutation belongs, remove the common
// first number from the list and append it to the resulting string, and iteratively
// construct the (((k - 1) % (n - 1)!) + 1)-th permutation with the remaining n-1 numbers
int group = total;
stringstream permutation;
while (n > 0) {
group /= n;
int idx = (k - 1) / group;
permutation << nums[idx];
nums.erase(nums.begin() + idx);
k = (k - 1) % group + 1;
--n;
}
return permutation.str();
}
};