forked from algorithm024/algorithm024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermute_46.java
More file actions
36 lines (32 loc) · 1.03 KB
/
Copy pathPermute_46.java
File metadata and controls
36 lines (32 loc) · 1.03 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
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Permute_46 {
private int n;
public List<List<Integer>> permute(int[] nums) {
n = nums.length;
List<List<Integer>> res = new ArrayList<>();
if (nums == null || n == 0) {
return res;
}
List<Integer> path = new ArrayList<>();
for (int num : nums) {
path.add(num);
}
backtrack(0, path, res);
return res;
}
private void backtrack(int first, List<Integer> path, List<List<Integer>> res) {
if (first == n) {
// 这里陷阱不能直接add(path),path为引用型变量实际存的list就始终变成了一个
// res.add(path);
res.add(new ArrayList<Integer>(path));
return;
}
for (int i = first; i < n; i++) {
Collections.swap(path, first, i);
backtrack(first + 1, path, res);
Collections.swap(path, first, i);
}
}
}