LeetCode 47. 全排列 II
原题链接
中等
作者:
LangB
,
2020-10-30 20:31:52
,
所有人可见
,
阅读 264
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
boolean[] used = new boolean[nums.length];
Arrays.sort(nums);
dfs(nums, new ArrayList<Integer>(), used);
return res;
}
private void dfs(int[] nums, List<Integer> path, boolean[] used) {
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
// 去重
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
continue;
}
if (!used[i]) {
used[i] = true;
path.add(nums[i]);
dfs(nums, path, used);
path.remove(path.size() - 1);
used[i] = false;
}
}
}
}