forked from yuduozhou/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPermutationSequence.java
99 lines (91 loc) · 2.56 KB
/
PermutationSequence.java
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Done via NextPermutation
public class Solution {
public String getPermutation(int n, int k) {
// Start typing your Java solution below
// DO NOT write main() function
int [] num = new int[n];
for (int i = 1; i <= n; i ++){
num[i - 1] = i;
}
int j = 1;
while (j < k){
nextPermutation(num);
j++;
}
String result = "";
for (int i : num){
result += i;
}
return result;
}
public void nextPermutation(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
int n = num.length;
for (int i = n - 1; i >= 1; i--) {
if (num[i] > num[i-1]) {
//swap the 2 numbers
swapRange(num, i, n-1);
for (int j = i; j < n; j++) {
if (num[j]>num[i-1]) {
swap(num, i-1, j);
return;
}
}
}
}
//swap each pair
swapRange(num, 0, n-1);
}
public void swapRange(int[] num, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
swap(num, i, j);
}
}
public void swap(int[] num, int i, int j) {
if (num[i] == num[j]) return;
num[i] = num[i]^num[j];
num[j] = num[i]^num[j];
num[i] = num[i]^num[j];
}
}
// Magic way by heartfire.cc
// What's him doing?
public class Solution {
public String getPermutation(int n, int k) {
// Start typing your Java solution below
// DO NOT write main() function
if (n==1) {
return "1";
}
int fac = 1; //n-1 factorial
for (int i = 1; i <= n-1; i++) {
fac *= i;
}
StringBuilder sb = new StringBuilder();
boolean[] used = new boolean[n];
for (int i = 0; i < n; i++) {
used[i] = false;
}
k--; //k starting from 1 is messing things up
for (int i = 0; i < n; i++) {
int d = k/fac + 1; //d-th available number
int j = 0;
for (; j < n; j++) {
if (used[j] == false) {
d--;
}
if (d == 0) {
break;
}
}
used[j] = true;
sb.append(j+1);
if (i < n-1) {
k = k%fac;
fac = fac/(n-1-i);
}
}
return sb.toString();
}
}