forked from damaohongtu/JavaInterview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutationSequence.java
More file actions
49 lines (43 loc) · 1.24 KB
/
PermutationSequence.java
File metadata and controls
49 lines (43 loc) · 1.24 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package LeetCode;
import java.util.ArrayList;
import java.util.List;
public class PermutationSequence {
public String getPermutation(int n, int k) {
int[] nums=new int[n];
for(int i=0;i<n;i++){
nums[i]=i+1;
}
List<List<Integer>> lists=permute(nums);
String result="";
for(int i:lists.get(k-1)){
result+=i;
}
return result;
}
List<List<Integer>> lists;
public List<List<Integer>> permute(int[] nums) {
lists = new ArrayList<List<Integer>>();
helper(nums, 0, nums.length, new ArrayList<Integer>());
return lists;
}
private void helper(int[] nums, int start, int length, List<Integer> list) {
if (list.size() == length) {
lists.add(new ArrayList<Integer>(list));
return;
}
if (start >= length) {
return;
}
for (int i = 0; i < length; i++) {
if (list.contains(nums[i])) {
continue;
}
// Choose
list.add(nums[i]);
// Explore
helper(nums, i, length, new ArrayList<Integer>(list));
// UnChoose
list.remove(list.size() - 1);
}
}
}