-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutations.java
More file actions
52 lines (45 loc) · 1.61 KB
/
Copy pathPermutations.java
File metadata and controls
52 lines (45 loc) · 1.61 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
50
51
52
import java.util.ArrayList;
import java.util.List;
class MySolution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
helper(result, new ArrayList<>(), nums, i);
}
return result;
}
public void helper(List<List<Integer>> result, List<Integer> currPermutation, int[] nums, int index) {
if (currPermutation.size() == nums.length) {
result.add(new ArrayList<>(currPermutation));
return;
}
if (index == nums.length) {
return;
}
currPermutation.add(nums[index]);
helper(result, currPermutation, nums, index+1);
currPermutation.remove(currPermutation.size()-1);
helper(result, currPermutation, nums, index+1);
}
}
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> answer = new ArrayList<>();
backtrack(answer, new ArrayList<>(), nums);
return answer;
}
public void backtrack(List<List<Integer>> answer, List<Integer> currPermutation, int[] nums) {
if (currPermutation.size() == nums.length) {
answer.add(new ArrayList<>(currPermutation));
}
else {
for (int i = 0; i < nums.length; i++) {
if (currPermutation.contains(nums[i]))
continue;
currPermutation.add(nums[i]);
backtrack(answer, currPermutation, nums);
currPermutation.remove(currPermutation.size() - 1);
}
}
}
}