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].
这个方法同样可以解决Permutations问题,更改其中的ArrayList为HashSet即可。
思路类似:list加入1,2加入1前,1后,list变为1,2;和2,1;同理插入3,list变为
3,1,2;1,3,2;1,2,3;3,2,1;2,3,1;2,1,3;
public static ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
ArrayList<ArrayList<Integer>> returnList = new ArrayList<ArrayList<Integer>>();
returnList.add(new ArrayList<Integer>());
for (int i = 0; i < num.length; i++) {
HashSet<ArrayList<Integer>> currentSet = new HashSet<ArrayList<Integer>>();
for (List<Integer> l : returnList) {
for (int j = 0; j < l.size() + 1; j++) {
l.add(j, num[i]);
ArrayList<Integer> T = new ArrayList<Integer>(l);
l.remove(j);
currentSet.add(T);
}
}
returnList = new ArrayList<ArrayList<Integer>>(currentSet);
}
return returnList;
}