Skip to content

Commit 029e01b

Browse files
committed
permutation sequence
1 parent c8b1ae1 commit 029e01b

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package backtracking;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
// https://leetcode.com/problems/permutation-sequence/
7+
public class PermutationSequence {
8+
9+
public static void main(String[] args) {
10+
PermutationSequence obj = new PermutationSequence();
11+
String result = obj.getPermutation(4, 9);
12+
System.out.println("result > " + result);
13+
}
14+
15+
public String getPermutation(int n, int k) {
16+
// factorial
17+
int[] factorial = new int[n + 1];
18+
factorial[0] = 1;
19+
int sum = 1;
20+
21+
// create an array of factorial lookup
22+
for (int i = 1; i <= n; i++) {
23+
sum *= i;
24+
// factorial[] = {1, 1, 2, 6, 24, ..., n!}
25+
factorial[i] = sum;
26+
}
27+
28+
// create a list of numbers to get indices
29+
List<Integer> items = new ArrayList<Integer>();
30+
for (int i = 1; i <= n; i++) {
31+
// numbers = {1, 2, 3, 4}
32+
items.add(i);
33+
}
34+
35+
// i from 0, so k - 1
36+
k--;
37+
38+
StringBuilder sb = new StringBuilder();
39+
// calculate
40+
for (int i = 1; i <= n; i++) {
41+
int index = k / factorial[n - i];
42+
int item = items.get(index);
43+
sb.append(String.valueOf(item));
44+
items.remove(index);
45+
k -= index * factorial[n - i];
46+
}
47+
48+
return sb.toString();
49+
}
50+
}

0 commit comments

Comments
 (0)