forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutationSequence.java
More file actions
90 lines (84 loc) · 2.46 KB
/
PermutationSequence.java
File metadata and controls
90 lines (84 loc) · 2.46 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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 count = 1;
while(count < k){
int index = 0;
for(int i = n - 1; i > 0; --i){
if(num[i] > num[i - 1]){
index = i - 1;
break;
}
}
for(int i = n - 1; i > index; --i){
if(num[i] > num[index]){
swap(num, i, index);
break;
}
}
for(int i = n - 1, j = index + 1; i > j; --i, ++j){
swap(num, i, j);
}
count++;
}
String result = "";
for(int i = 0; i < n; ++i)
result += String.valueOf(num[i]);
return result;
}
public void swap(int[] num, int i, int j){
int tmp = num[i];
num[i] = num[j];
num[j] = tmp;
}
}
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 = 0; i < n; ++i)
num[i] = i + 1;
for(int i = 2; i <= k; ++i){
nextPermutation(num);
}
StringBuffer sb = new StringBuffer();
for(int val: num)
sb.append(val);
return sb.toString();
}
public void nextPermutation(int[] num){
int pivot = -1;
for(int i = num.length - 1; i > 0; --i){
if(num[i - 1] < num[i]){
pivot = i - 1;
break;
}
}
if(pivot == -1){
for(int i = 0; i < num.length; ++i)
num[i] = i + 1;
return;
}
for(int i = num.length - 1; i > pivot; --i){
if(num[i] > num[pivot]){
swap(num, i, pivot);
break;
}
}
for(int i = num.length - 1, j = pivot + 1; i > j;){
swap(num, i, j);
--i;
++j;
}
}
public void swap(int[] num, int i, int j){
int tmp = num[i];
num[i] = num[j];
num[j] = tmp;
}
}