-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBM55.java
More file actions
56 lines (48 loc) · 1.45 KB
/
BM55.java
File metadata and controls
56 lines (48 loc) · 1.45 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
package NiukeTOP101;
import java.util.ArrayList;
public class BM55 {
ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<Integer> ans = new ArrayList<>();
dfs(num, ans);
return ret;
}
private void dfs(int[] num, ArrayList<Integer> ans) {
if(ans.size() == num.length){
ret.add(new ArrayList<>(ans));
return;
}
for (int i = 0; i < num.length; i++) {
if(ans.contains(num[i])){
continue;
}
ans.add(num[i]);
dfs(num, ans);
ans.remove(ans.size() - 1);
}
}
}
class BM55_1{
ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
ArrayList<Integer> tempList = new ArrayList<>();
public ArrayList<ArrayList<Integer>> permute(int[] num) {
boolean[] numState = new boolean[num.length];
backTracking(num, numState);
return ret;
}
private void backTracking(int[] num, boolean[] numState) {
if(tempList.size() == num.length){
ret.add(new ArrayList<>(tempList));
return;
}
for (int i = 0; i < num.length; i++) {
if(numState[i]){
continue;
}
tempList.add(num[i]);
numState[i] = true;
backTracking(num, numState);
tempList.remove(tempList.size() - 1);
}
}
}