class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
// 排序
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
int[] visited = new int[nums.length];
dfs(nums, visited, new ArrayList<>(), res);
return res;
}
private void dfs(int[] nums, int[] visited, ArrayList<Integer> path, List<List<Integer>> res) {
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i] == 1) continue;
// 写 visited[i - 1] == 0 是因为 nums[i - 1] 在深度优先遍历的过程中刚刚被撤销选择
if (i > 0 && nums[i] == nums[i - 1] && visited[i - 1] == 0) continue;
visited[i] = 1;
path.add(nums[i]);
dfs(nums, visited, path, res);
visited[i] = 0;
path.remove(path.size() - 1);
}
}
}
leetcode刷题之路-47. 全排列 II
最新推荐文章于 2024-07-25 21:13:04 发布