DFS {1, 1, 1, 2} 4 Situation before list.remove(list.size()-1)
1, 1 1, 1 1 1, 1 1 1 2;
when we operating 1 1, we can directly put 2 after 1 1.
进入下一层递归前,把和当前位重复的数过Skip.
public List<List<Integer>> permuteUnique(int[] num) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
ArrayList<Integer> temp = new ArrayList<Integer>();
Arrays.sort(num);
boolean[] visited = new boolean[num.length];
permuteUniqueHelper(result, temp, num, visited);
return result;
}
private void permuteUniqueHelper(List<List<Integer>> result, ArrayList<Integer> list, int[] num, boolean[] visited) {
if (list.size() == num.length) {
result.add(new ArrayList<Integer>(list));
return;
}
for (int i=0; i<num.length; i++) {
if (!visited[i]) {
visited[i] = true;
list.add(num[i]);
permuteUniqueHelper(result, list, num, visited);
list.remove(list.size()-1);
visited[i] = false;
while (i<num.length-1 && num[i+1]==num[i]) {
i++;
}
}
}
}
No comments:
Post a Comment