题目描述
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
输入示例
nums = [1,1,2]
输出示例
[[1,1,2], [1,2,1], [2,1,1]]
解题思路
解题代码
class Solution {List<List<Integer>> result = new ArrayList<>();Deque<Integer> path = new ArrayDeque<>();public List<List<Integer>> permuteUnique(int[] nums) {int n = nums.length;boolean[] used = new boolean[n];backtrack(nums, used);return result;}public void backtrack(int[] nums, boolean[] used) {if(path.size() == nums.length) {result.add(new ArrayList<Integer>(path));return;}Set<Integer> set = new HashSet<>();for(int i = 0; i < nums.length; i++) {if(used[i] == true || set.contains(nums[i])) {continue;}path.addLast(nums[i]);set.add(nums[i]);used[i] = true;backtrack(nums, used);used[i] = false;path.removeLast();}}
}