forked from yuanx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutationSequence.java
More file actions
82 lines (67 loc) · 1.89 KB
/
PermutationSequence.java
File metadata and controls
82 lines (67 loc) · 1.89 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
// Recursively find the kth large number, slow, could not pass the large test.
public class Solution {
public String getPermutation(int n, int k) {
// Start typing your Java solution below
// DO NOT write main() function
int[] count = new int[1]; //use this to count;
int[] used = new int[n];
int[] re = new int[n];
int[] cal = new int[n];
getkthPermutation(count, used, k, re, cal, 0);
StringBuilder sb = new StringBuilder();
for(int i=0; i<re.length; i++){
sb.append(Integer.toString(re[i]));
}
return sb.toString();
}
public void getkthPermutation(int[] count, int[] used, int k, int[] re, int[] cal, int level){
if(count[0]==k)
return;
if(cal.length == level){
count[0]++;
if(count[0] == k)
for(int i=0; i<cal.length; i++)
re[i]=cal[i];
return;
}
for(int i=0; i<cal.length; i++){
if(used[i] == 0){
cal[level] = i+1;
used[i]=1;
getkthPermutation(count, used, k, re, cal, level+1);
used[i]=0;
}
}
}
}
// Directly form the kth large number, faster, pass both test
public class Solution {
public String getPermutation(int n, int k) {
// Start typing your Java solution below
// DO NOT write main() function
int dividend = k-1;
int[] dividors = new int[n-1];
String t = "123456789";
for(int i=0; i<n-1; i++){
dividors[i]= factorial(n-1-i);
}
StringBuilder sb = new StringBuilder();
int j=0;
while(j<n-1){
int result = dividend/dividors[j];
int remainder = dividend%dividors[j];
sb.append(t.charAt(result));
t = t.substring(0,result) + t.substring(result+1);
dividend = remainder;
j++;
}
sb.append(t.charAt(dividend));
return sb.toString();
}
public int factorial(int n){
int sum = 1;
while(n>0)
sum*=(n--);
return sum;
}
}