forked from MaskRay/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutation-sequence.cc
More file actions
68 lines (61 loc) · 1.23 KB
/
permutation-sequence.cc
File metadata and controls
68 lines (61 loc) · 1.23 KB
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
66
67
68
// Permutation Sequence
#define ROF(i, a, b) for (int i = (b); --i >= (a); )
class Solution {
public:
string getPermutation(int n, int k) {
int f[] = {1,1,2,6,24,120,720,5040,40320};
vector<bool> a(n, true);
string r;
k--;
ROF(i, 0, n) {
int t = k/f[i], j = 0;
k %= f[i];
while (! a[j]) j++;
while (t--)
while (! a[++j]);
a[j] = false;
r += '1'+j;
}
return r;
}
};
// bit twiddling
#define ROF(i, a, b) for (int i = (b); --i >= (a); )
class Solution {
public:
string getPermutation(int n, int k) {
int f[] = {1,1,2,6,24,120,720,5040,40320};
int a = ~0;
string r;
k--;
ROF(i, 0, n) {
int t = k/f[i];
k %= f[i];
int b = a;
while (t--)
b &= b-1;
int j = __builtin_ctz(b);
a ^= 1<<j;
r += '1'+j;
}
return r;
}
};
// 陈霜
#define ROF(i, a, b) for (int i = (b); --i >= (a); )
class Solution {
public:
string getPermutation(int n, int k) {
int f[] = {1,1,2,6,24,120,720,5040,40320};
long long a = 0x987654321;
string r;
k--;
ROF(i, 0, n) {
int t = k/f[i];
k %= f[i];
r += '0'|a>>4*t&15;
a = a&(1LL<<4*t)-1|a>>4*(t+1)<<4*t;
}
return r;
}
};