题目:
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]
.
思路:
1) 直接利用permutation的代码,可以利用list.contains(o)的方法来去除重复【returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e))】
2) 和Permutation一样,排序之后,不断的见缝插针,遇到重复时,只在这个这个值的前面插入,然后就break,为什么呢?因为已经形成的集合具有对称性,所以我们就只在重复值的左边插入。当然,你也可以只在重复值的右边插入。
package permutation; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class PermutationsII { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); Arrays.sort(nums); List<Integer> subRes = new ArrayList<Integer>(); subRes.add(nums[0]); res.add(subRes); return permute(res, nums, 1); } private List<List<Integer>> permute(List<List<Integer>> res, int[] nums, int pos) { if (pos >= nums.length) return res; List<List<Integer>> newRes = new ArrayList<List<Integer>>(); for (List<Integer> subRes : res) { int count = subRes.size(); for (int i = 0; i <= count; ++i) { if (i > 0 && nums[pos] == subRes.get(i - 1)) break; List<Integer> newSubRes = new ArrayList<Integer>(subRes); newSubRes.add(i, nums[pos]); newRes.add(newSubRes); } } return permute(newRes, nums, pos + 1); } public static void main(String[] args) { // TODO Auto-generated method stub PermutationsII p = new PermutationsII(); int[] nums = { 2,2,1,1 }; List<List<Integer>> res = p.permuteUnique(nums); for (List<Integer> l : res) { for (int i : l) System.out.print(i + " "); System.out.println(); } } }