给定一个可包含重复数字的序列 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
class Solution {
boolean[] used; //判重
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
used = new boolean[nums.length];
List<List<Integer>> res = new ArrayList<>();
dfs(nums, new ArrayList<Integer>(), res);
return res;
}
private void dfs(int[] nums, List<Integer> path, List<List<Integer>> res) {
if (path.size() == nums.length) {
res.add(new ArrayList<Integer>(path));
return;
}
for (int i = 0; i < nums.length; ++i) {
//[1,1,2]判重,同一层的不能选一样的
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, res);
path.remove(path.size() - 1);
used[i] = false;
}
}
}
}