-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathPermutationSequence.java
More file actions
28 lines (28 loc) · 1.01 KB
/
PermutationSequence.java
File metadata and controls
28 lines (28 loc) · 1.01 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
public class PermutationSequence {
public String getPermutation(int n, int k) {
int fact = 1;
// use a list to store all left numbers
List<Integer> nums = new LinkedList<>();
for (int i = 1; i <= n; i++) {
fact *= i;
nums.add(i);
}
// if k is larger than n!, process k first.
k = (k - 1) % fact + 1;
StringBuilder sb = new StringBuilder();
for (int i = n; i > 0; i--) {
// f is the factorial without the current number
// use f to get which number should be next number
int f = fact / i;
// the index to indicate which number in the left numbers list
int index = (k - 1) / f;
sb.append(nums.get(index));
// should remove every number has been used
nums.remove(index);
// update k, minus the number of permutations before
k = k - index * f;
fact = f;
}
return sb.toString();
}
}