permutation template


https://leetcode.com/problems/permutations/
模板一样的题。背诵并理解全文。

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
List<List<Integer>> ans;

public List<List<Integer>> permute(int[] nums) {
Arrays.sort(nums);
ans = new ArrayList<List<Integer>>();
HashSet<Integer> visited = new HashSet<Integer>();
List<Integer> path = new ArrayList<Integer>();
dfs(nums, path, visited);
return ans;
}

public void (int[] nums, List<Integer> path, HashSet<Integer> visited) {
if (path.size() == nums.length) {
ans.add(new ArrayList<Integer>(path));
return;
}
for (int i = 0; i < nums.length; ++i) {
if (visited.contains(nums[i]))
continue;
visited.add(nums[i]);
path.add(nums[i]);
dfs(nums, path, visited);
path.remove(path.size() - 1);
visited.remove(nums[i]);
}
}