-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
27 lines (25 loc) · 786 Bytes
/
Solution.java
File metadata and controls
27 lines (25 loc) · 786 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
package leetcode._60_;
import java.util.ArrayList;
import java.util.List;
class Solution {
public String getPermutation(int n, int k) {
int[] factorial = new int[n + 1];
List<Integer> leftNumList = new ArrayList<>();
int sum = 1;
factorial[0] = 1;
for (int i = 1; i <= n; i++) {
leftNumList.add(i);
sum *= i;
factorial[i] = sum;
}
StringBuilder stringBuilder = new StringBuilder();
k--; // Amazing k--
for (int i = 1; i <= n; i++) {
int index = k / factorial[n - i];
k = k % factorial[n - i];
stringBuilder.append(leftNumList.get(index));
leftNumList.remove(index);
}
return stringBuilder.toString();
}
}