47. 全排列 II
难度中等754
给定一个可包含重复数字的序列 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]]
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
//path记录已选值,res记录已选索引
List<Integer> path = new ArrayList<>();
boolean[] used = new boolean[nums.length];
dfs(nums, path, used);
return res;
}
public 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(used[i]) continue;
//nums[i - 1]上层已选择中没有,并且和本次要做的选择相等
if(i > 0 && nums[i - 1] == nums[i] && used[i - 1] == false) {
continue;
}
path.add(nums[i]);
used[i] = true;
dfs(nums, path, used);
used[i] = false;
path.remove(path.size() - 1);
}
}
}