Difficulty:: Medium
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
1 2 3 4 5 6 7
| Input: [1,1,2] Output: [ [1,1,2], [1,2,1], [2,1,1] ]
|
Solution
Language: Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Solution { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> result = new ArrayList<>(); if (nums == null || nums.length == 0) { return result; } Arrays.sort(nums); boolean[] visited = new boolean[nums.length]; dfsHelper(nums, result, new ArrayList<Integer>(nums.length), visited); return result; } private void dfsHelper(int[] nums, List<List<Integer>> result, List<Integer> p, boolean[] visited) { if (p.size() == nums.length) { result.add(new ArrayList<>(p)); return; } for (int i = 0; i < nums.length; i++) { if (visited[i]) { continue; } if (i > 0 && nums[i] == nums[i - 1] && visited[i - 1]) { continue; } p.add(nums[i]); visited[i] = true; dfsHelper(nums, result, p, visited); visited[i] = false; p.remove(p.size() - 1); } } }
|