标签:
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]
.
思路:递归地将每个元素与第一个元素进行交换。有一个额外的空间Set<Integer> duplicated,如果某个元素已经与第一个元素进行交换,则与这个元素相同的元素就不需要再与第一个元素交换。
代码如下:
List<List<Integer>> lists = new ArrayList<List<Integer>>(); public List<List<Integer>> permuteUnique(int[] num) { permuteHelp(num, 0); return lists; } public void permuteHelp(int[] num, int start) { Set<Integer> duplicated = new HashSet<Integer>(); if(start == num.length-1) { List<Integer> list = new ArrayList<Integer>(); for(int i=0; i<num.length; i++) { list.add(num[i]); } lists.add(list); } else { for(int i=start; i<num.length; i++) { if(duplicated.contains(new Integer(num[i]))) continue; duplicated.add(new Integer(num[i])); swap(num, start, i); permuteHelp(num, start+1); swap(num, start, i); } } } public void swap(int[] num, int a, int b) { int tmp = num[a]; num[a] = num[b]; num[b] = tmp; }
标签:
原文地址:http://www.cnblogs.com/linxiong/p/4298421.html