Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2] Output: [ [1,1,2], [1,2,1], [2,1,1] ]
boolean数组不需要初始化,默认都是false
有重复的判断条件中,要加i > 0
!used[i - 1],前一个元素还没用过 就找下一个元素了 不行
class Solution { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> list = new ArrayList<>(); boolean[] used = new boolean[nums.length]; Arrays.sort(nums); backtrack(nums, new ArrayList<>(), used, list); return list; } private void backtrack(int [] nums, List<Integer> tempList, boolean[] used, List<List<Integer>> list){ if (tempList.size() == nums.length) list.add(new ArrayList<>(tempList)); for(int i = 0; i < nums.length; i++){ if(used[i] || (i > 0 && (nums[i] == nums[i - 1] && !used[i - 1]))) continue; tempList.add(nums[i]); used[i] = true; backtrack(nums, tempList, used, list); tempList.remove(tempList.size() - 1); used[i] = false; } } }