Skip to content

Commit 9b2a601

Browse files
author
tanfanhua
committed
permutation
1 parent 5be274c commit 9b2a601

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.blankj.medium._060;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
public class Solution {
7+
8+
public static void main(String[] args) {
9+
Solution s = new Solution();
10+
System.out.println(s.permutationSequence(4, 9));
11+
}
12+
13+
public String permutationSequence(int n, int k) {
14+
if (n <= 0 || k <= 0) {
15+
return "";
16+
}
17+
18+
List<String> elements = new ArrayList<>();
19+
for (int i = 1; i <= n; i++) {
20+
elements.add(String.valueOf(i));
21+
}
22+
List<String> res = dfsPermutation(elements);
23+
if (k > res.size()) {
24+
throw new IllegalArgumentException("k is bigger than permutation list size");
25+
}
26+
27+
return res.get(k);
28+
}
29+
30+
public List<String> dfsPermutation(List<String> elements) {
31+
List<String> res = new ArrayList<>();
32+
if (elements.size() == 1) {
33+
res.add(elements.get(0));
34+
} else {
35+
for (String e : elements) {
36+
List<String> left = new ArrayList<>();
37+
for (String l : elements) {
38+
if (l != e) {
39+
left.add(l);
40+
}
41+
}
42+
List<String> subsequences = dfsPermutation(left);
43+
for (String sub : subsequences) {
44+
res.add(e + sub);
45+
}
46+
}
47+
}
48+
49+
return res;
50+
}
51+
52+
53+
}

0 commit comments

Comments
 (0)