forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
60.cpp
65 lines (51 loc) · 1.4 KB
/
60.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
string getPermutation(int n, int k) {
if (k == 0) return "";
string ans;
vector<int> nums(n); /* numbers from 1 to n */
vector<bool> flag(n, false);
for (int i = 0; i < n; i++) {
nums[i] = i + 1;
}
getPermutationHelper(ans, nums, flag, n, k);
return ans;
}
void getPermutationHelper(string &ans, vector<int> nums, vector<bool> &flag, int n, int k) {
if (n == 0) return;
int fact = 1; /* factorial of (n - 1) */
for (int i = 1; i <= n - 1; i++) {
fact *= i;
}
int first = 0; /* pick the first available number as head of permutation */
while (flag[first]) { /* skip unavailable numbers */
first++;
}
while (k > fact) {
first++;
while (flag[first]) { /* skip unavailable numbers */
first++;
}
k -= fact;
}
flag[first] = true;
ans.push_back(nums[first] + '0');
getPermutationHelper(ans, nums, flag, n - 1, k);
}
};
int main() {
int n = 3;
int factN = 1;
for (int i = 1; i <= n; i++) {
factN *= i;
}
Solution s;
for (int k = 1; k <= factN; k++) {
cout << s.getPermutation(n, k) << endl;
}
return 0;
}