-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpermutationsII.java
More file actions
93 lines (90 loc) · 3.16 KB
/
permutationsII.java
File metadata and controls
93 lines (90 loc) · 3.16 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class permutationsII {
public static void main(String[] args){
permutationsII obj = new permutationsII();
int[] nums = {1, 2, 3};
System.out.println(obj.permute(nums));
System.out.println(obj.permutev2(nums));
}
/* Approach 1: dfs 画出recursion tree
empty
/ | \
1 2 3
/ \ / \ / \
2 3 1 3 1 2
| | | | | |
3 2 3 1 2 1
* */
private List<List<Integer>> permute(int[] nums){
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
List<Integer> eles = new ArrayList<>();
for(int num : nums){
eles.add(num);
}
List<Integer> path = new ArrayList<>();
dfs(path, res, eles);
return res;
}
private void dfs(List<Integer> path, List<List<Integer>> res, List<Integer> nums){
if(nums.size() ==0 ){
res.add(new ArrayList<>(path));
return;
}
for(int i=0; i<nums.size(); i++){
/* remove duplicates
In the recursion tree, for each node, we need to remove duplicate branches.
* */
if(i > 0 && nums.get(i) == nums.get(i-1)){
continue;
}
int cur = nums.get(i);
path.add(cur);
nums.remove(i);
dfs(path, res, nums);
nums.add(i,cur);
path.remove(path.size()-1);
}
}
// Approach 2: optimize approach 1. Use a boolean array instead of remove/add elements from arraylist everytime.
private List<List<Integer>> permutev2(int[] nums){
Arrays.sort(nums);
// if nums is a arraylist: Collections.sort(nums)
List<List<Integer>> res = new ArrayList<>();
boolean[] visited = new boolean[nums.length];
System.out.println(Arrays.toString(visited));
List<Integer> path = new ArrayList<>();
dfs2(path, nums, visited, res);
return res;
}
private void dfs2(List<Integer> path, int[] nums, boolean[] visited, List<List<Integer>> res){
// base case:
if(path.size() == nums.length){
res.add(new ArrayList<>(path));
return;
}
for(int i=0; i < nums.length; i++){
if(visited[i]){
continue;
}
// 其实还包含隐含条件
/* 这个去重条件是自己想出来的,跟标准答案不太一样,但是更加prefer自己的
1 2 2
V N N 这种条件下第二个2被跳过了,不然会构建两个 "1 2"
1 2 2
V V N 在这种条件下就不能跳过第二个2, 因为在构建 "1 2 2"
* */
if(i>0 && !visited[i-1] && nums[i] == nums[i-1]){
continue;
}
visited[i] = true;
path.add(nums[i]);
dfs2(path, nums, visited, res);
path.remove(path.size()-1);
visited[i] = false;
}
}
}