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:
这个题跟Permutations非常类似,唯一的区别就是在这个题目中元素集合可以出现重复。这给我们带来一个问题就是如果不对重复元素加以区别,那么类似于{1,1,2}这样的例子我们会有重复结果出现。那么如何避免这种重复呢?方法就是对于重复的元素循环时跳过递归函数的调用,只对第一个未被使用的进行递归,我们那么这一次结果会出现在第一个的递归函数结果中,而后面重复的会被略过。如果第一个重复元素前面的元素还没在当前结果中,那么我们不需要进行递归。想明白了这一点,代码其实很好修改。首先我们要对元素集合排序,从而让重复元素相邻,接下来就是一行代码对于重复元素和前面元素使用情况的判断即可。
Reference: http://blog.csdn.net/linhuanmars/article/details/21570835public class Solution {
public ArrayList> permuteUnique(int[] num) {
ArrayList> res = new ArrayList>();
if(num == null || num.length == 0)
return res;
Arrays.sort(num);
boolean[] used = new boolean[num.length];
ArrayList list = new ArrayList();
helper(num, res, list, used);
return res;
}
public void helper(int[] num, ArrayList> res, ArrayList list, boolean[] used) {
if(list.size() == num.length) {
res.add(new ArrayList (list));
return;
}
for(int i = 0; i < num.length; i++) {
if(i > 0 && !used[i - 1] && num[i] == num[i - 1])
continue;
if(!used[i]) {
used[i] = true;
list.add(num[i]);
helper(num, res, list, used);
list.remove(list.size() - 1);
used[i] = false;
}
}
}
}
No comments:
Post a Comment