leetcode-47. 全排列 II

原始思路

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
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> ans = new ArrayList<>();
Set<Integer> set = new HashSet<>();
Set<List<Integer>> setAns = new HashSet<>();
public List<List<Integer>> permuteUnique(int[] nums) {
dfs(0, nums);
return result;
}

public void dfs(int cur, int[] nums){
if(cur >= nums.length){
return;
}

if(ans.size() == nums.length){
if(!setAns.contains(ans)){
setAns.add(ans);
result.add(new ArrayList(ans));
}
return;
}

for(int i = cur; i < nums.length; i++){
if(set.contains(i)){
continue;
}
set.add(i);
ans.add(nums[i]);
dfs(cur, nums);
ans.remove(ans.size() -1);
set.remove(i);
}
}
}