forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutationsequence.java
More file actions
executable file
·37 lines (35 loc) · 918 Bytes
/
permutationsequence.java
File metadata and controls
executable file
·37 lines (35 loc) · 918 Bytes
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
public class Solution {
public String getPermutation(int n, int k) {
// Start typing your Java solution below
// DO NOT write main() function
if(n==0) return "";
if(n==1) return "1";
int t = 1;
int sn = n;
k--;
while(sn-1>0){
t*=(sn-1);
sn--;
}
boolean tt[] = new boolean[n];
StringBuilder sb = new StringBuilder("");
for(int i=0;i<n;i++){
int r = k/t;
k %= t;
if(n-1-i!=0){
t /= (n-1-i);
}
int j=0;
int kk=0;
while(j<r || tt[kk] == true ){
if(tt[kk]==false){
j++;
}
kk++;
}
tt[kk] = true;
sb.append((char)(kk+'1'));
}
return sb.toString();
}
}