目录
47. 全排列 II
题目描述:
给定一个可包含重复数字的序列 nums
,按任意顺序 返回所有不重复的全排列。
示例 1:
输入:nums = [1,1,2] 输出: [[1,1,2], [1,2,1], [2,1,1]]
示例 2:
输入:nums = [1,2,3] 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
提示:
1 <= nums.length <= 8
-10 <= nums[i] <= 10
实现代码与解析:
dfs
class Solution {
public List<List<Integer>> res = new ArrayList<List<Integer>>();
public boolean[] hash;
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
hash = new boolean[nums.length];
dfs(nums, 0, new ArrayList<>());
return res;
}
public void dfs(int[] nums, int cur, List<Integer> list) {
if (cur == nums.length) {
res.add(new ArrayList<Integer>(list));
return;
}
for (int i = 0; i < nums.length; i++) {
if (hash[i] || (i > 0 && nums[i] == nums[i - 1] && !hash[i - 1])) {
continue;
}
hash[i] = true;
list.add(nums[i]);
dfs(nums, cur + 1, list);
hash[i] = false;
list.remove(list.size() - 1);
}
}
}
原理思路:
dfs回溯求解,hash记录是否使用过该数字,如果已经用过跳过。
重点是这个nums[i] == nums[i - 1] && !hash[i - 1],因为需要去掉重复的,因为里面有重复的数字,所以每个位置可能重复,先排序,然后判断,如果和上一个数相同,并且上一个数没有使用过的话就跳过。