转自:http://www.cnblogs.com/longhorn/p/3527824.html
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]
.
有重复数字的话,用递归就不是很好做。每一次产生一个结果就要判断这个结果是否已经包含在result中,所以时间长。
用dfs做的话用两个地方需要注意。
一个是要对字符串进行排序。因为如果排序的话,可以很好避免因为重复数字产生的重复的情况。
第二个就是如何避免因为重复数字产生的重复情况。因为已经排好序,所以每次选择下一个数字的时候只要避免和之前的数字重复就行。
比如[1,2,3,3,4].当我们产生[1,2,3]的时候,我们只要避免回溯的时候再次选择3,从而产生[1,2,3]就行了。
public class Solution {
public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
Arrays.sort(num);
boolean[] visited = new boolean[num.length];
ArrayList<Integer> tmp = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
permute2(num, visited, tmp, result);
return result;
}
public static void permute2(int[] num, boolean[] visited, ArrayList<Integer> tmp, ArrayList<ArrayList<Integer>> result) {
if (tmp.size() == num.length) {
result.add(new ArrayList<Integer>(tmp));
return;
}
for (int i=0; i<num.length; i++) {
if (visited[i] == false) {
tmp.add(num[i]);
visited[i] = true;
permute2(num, visited, tmp, result);
visited[i] = false;
tmp.remove(tmp.size()-1);
<span style="background-color: rgb(255, 0, 0);"> while (i<num.length-1 && num[i] == num[i+1]) i++;</span>
}
}
}
}