47. Permutations II
https://leetcode.com/problems/permutations-ii/
Related problems
46-permutations
78-subsets
90-subsets-ii
39-combination-sum
---
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] ]---
Related problems
46-permutations
78-subsets
90-subsets-ii
39-combination-sum
---
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public List<List<Integer>> permuteUnique(int[] nums) { | |
Arrays.sort(nums); | |
List<List<Integer>> ans = new ArrayList<List<Integer>>(); | |
dfs(nums, new ArrayList<Integer>(), new HashSet<Integer>(), ans); | |
return ans; | |
} | |
private void dfs(int[] nums, List<Integer> prefix, Set<Integer> visited, List<List<Integer>> ans) { | |
if (prefix.size() == nums.length) { | |
ans.add(new ArrayList<Integer>(prefix)); | |
return; | |
} | |
for (int i = 0; i < nums.length; i++) { | |
if (visited.contains(i) || (i > 0 && nums[i] == nums[i - 1] && !visited.contains(i - 1))) { | |
continue; | |
} | |
visited.add(i); | |
prefix.add(nums[i]); | |
dfs(nums, prefix, visited, ans); | |
prefix.remove(prefix.size() - 1); | |
visited.remove(i); | |
} | |
} | |
} |