-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path46.java
131 lines (115 loc) · 3.16 KB
/
46.java
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
class Solution {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();
int[] nums;
public List<List<Integer>> permute(int[] nums) {
this.nums = nums;
Set<Integer> set = new HashSet<>();
for(int num:nums){
set.add(num);
}
dfs(0, set);
return ans;
}
private void dfs(int i, Set<Integer> set) {
if (i == nums.length) {
ans.add(new ArrayList<>(path));
return;
}
for (Integer j : set) {
path.add(j);
Set<Integer> t = new HashSet<>(set);
t.remove(j);
dfs(i + 1, t);
path.remove(j);
}
}
}
// 第二次做法:我真是天才
import java.util.ArrayList;
import java.util.HashSet;
class Solution {
private List<List<Integer>> ans = new ArrayList<>();
private List<Integer> path = new ArrayList<>();
private Set<Integer> set = new HashSet<>();
private int[] nums;
public List<List<Integer>> permute(int[] nums) {
this.nums = nums;
dfs();
return ans;
}
private void dfs(){
if(set.size()==nums.length){
ans.add(new ArrayList<>(path));
return;
}
for(int num:nums){
if(!set.contains(num)){
path.add(num);
set.add(num);
dfs();
path.remove(path.size()-1);
set.remove(num);
}
}
}
}
// 第三次做法,一种更加通用的方法
class Solution {
private List<List<Integer>> ans = new ArrayList<>();
private List<Integer> path = new ArrayList<>();
private int[] nums;
private Set<Integer> set = new HashSet<>();
private int length;
public List<List<Integer>> permute(int[] nums) {
this.nums = nums;
dfs();
return ans;
}
private void dfs() {
if (length == nums.length) {
ans.add(new ArrayList<>(path));
return;
}
for (int num : nums) {
if (!set.contains(num)) {
path.add(num);
set.add(num);
length++;
dfs();
length--;
path.remove(path.size()-1);
set.remove(num);
}
}
}
}
// 第四次做法:将length方法作为参数传入,便于通用方法
class Solution {
private List<List<Integer>> ans = new ArrayList<>();
private List<Integer> path = new ArrayList<>();
private int[] nums;
private Set<Integer> set = new HashSet<>();
public List<List<Integer>> permute(int[] nums) {
this.nums = nums;
dfs(0);
return ans;
}
private void dfs(int length) {
if (length == nums.length) {
ans.add(new ArrayList<>(path));
return;
}
for (int num : nums) {
if (!set.contains(num)) {
path.add(num);
set.add(num);
length++;
dfs(length);
length--;
path.remove(path.size()-1);
set.remove(num);
}
}
}
}