0%

LeetCode-47

题目

结果

代码

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
class Solution {
// Save the final answer
private final List<List<Integer>> ans = new ArrayList<>();
// Check out If the num has been used before
private boolean[] flag;

public List<List<Integer>> permuteUnique(int[] nums) {
// Special case
if (nums.length == 0) {
return ans;
}
// Initialize the flag array
flag = new boolean[nums.length];
dfs(nums, new ArrayList<>());
// Remove the duplicate and return the final answer
return ans.stream().distinct().collect(Collectors.toList());
}

private void dfs(int[] nums, List<Integer> tmp) {
// Time to stop recursive call
if (tmp.size() == nums.length) {
ans.add(tmp);
return;
}
for (int i = 0; i < nums.length; i++) {
if (!flag[i]) {
flag[i] = true;
List<Integer> newTmp = new ArrayList<>(tmp);
newTmp.add(nums[i]);
// Recursive call
dfs(nums, newTmp);
flag[i] = false;
}
}
}
}