Skip to content

Commit 3042be6

Browse files
committed
permutation sequence
1 parent 4f25543 commit 3042be6

File tree

3 files changed

+93
-41
lines changed

3 files changed

+93
-41
lines changed

.idea/workspace.xml

Lines changed: 48 additions & 41 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,3 +427,4 @@ codes may not be optimized
427427

428428
1. [Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset/description/)
429429
1. [Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/description/)
430+
1. [Permutation Sequence](https://leetcode.com/problems/permutation-sequence/description/)
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.github.chen0040.leetcode.day21.medium;
2+
3+
4+
import java.util.ArrayList;
5+
import java.util.List;
6+
7+
8+
/**
9+
* Created by xschen on 16/8/2017.
10+
*
11+
* link: https://leetcode.com/problems/permutation-sequence/description/
12+
*/
13+
public class PermutationSequence {
14+
public class Solution {
15+
String target;
16+
int count;
17+
public String getPermutation(int n, int k) {
18+
int[] factorial = new int[n];
19+
factorial[0] = 1;
20+
for(int i = 1; i < n; ++i) {
21+
factorial[i] = factorial[i-1] * i;
22+
}
23+
24+
k--;
25+
26+
List<Integer> nums = new ArrayList<Integer>();
27+
for(int i=0; i < n; ++i) {
28+
nums.add(i+1);
29+
}
30+
StringBuilder sb = new StringBuilder();
31+
for(int i=1; i <= n; ++i) {
32+
int index = k / factorial[n-i];
33+
sb.append(nums.get(index));
34+
nums.remove(nums.get(index));
35+
k -= index * factorial[n-i];
36+
}
37+
38+
return sb.toString();
39+
}
40+
41+
42+
43+
}
44+
}

0 commit comments

Comments
 (0)