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] ]
backtracking
和permutations不同的是可以有重复元素。先把数组排序。去重:在递归的时候判断当前元素与上一个元素是否相同,如果相同且上一个元素被访问过,跳过当前元素。
time: O(n! * n), space: O(n)
class Solution { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> permutations = new ArrayList<>(); boolean[] visited = new boolean[nums.length]; Arrays.sort(nums); backtracking(nums, permutations, new ArrayList<>(), visited); return permutations; } private void backtracking(int[] nums, List<List<Integer>> permutations, List<Integer> tmp, boolean[] visited) { if(tmp.size() == nums.length) permutations.add(new ArrayList<>(tmp)); for(int i = 0; i < nums.length; i++) { if(visited[i]) continue; if(i > 0 && nums[i] == nums[i-1] && visited[i-1]) continue; tmp.add(nums[i]); visited[i] = true; backtracking(nums, permutations, tmp, visited); visited[i] = false; tmp.remove(tmp.size() - 1); } } }