Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,[1,1,2]
have the following unique permutations:[1,1,2]
, [1,2,1]
, and [2,1,1]
.
Solution 1:
public List<List<Integer>> permuteUnique(int[] num) { List<List<Integer>> result = new ArrayList<>(); Arrays.sort(num); permutate(result, num, 0); return result; } public void permutate(List<List<Integer>> result, int[] num, int pos) { if(pos == num.length) { List<Integer> list = new ArrayList<Integer>(); for(int a:num) list.add(a); result.add(list); return; } for(int i=pos; i<num.length; i++) { if(hasDuplicate(num, pos, i)) continue; swap(num, i, pos); permutate(result, num, pos+1); swap(num, i, pos); } } private boolean hasDuplicate(int[] num, int start, int end) { for(int i=start; i<end; i++) { if(num[i] == num[end]) return true; } return false; } private void swap(int[] num, int i, int j) { int tmp = num[i]; num[i] = num[j]; num[j] = tmp; }
Solution 2:
public List<List<Integer>> permuteUnique(int[] num) { List<List<Integer>> result = new ArrayList<>(); result.add(new ArrayList<Integer>()); Arrays.sort(num); for(int i=0; i<num.length; i++) { Set<List<Integer>> currentSet = new HashSet<List<Integer>>(); for (List<Integer> l : result) { for (int j = 0; j < l.size() + 1; j++) { List<Integer> entry = new ArrayList<Integer>(l); entry.add(j, num[i]); currentSet.add(entry); } } result = new ArrayList<List<Integer>>(currentSet); } return result; }