全排列II
题目描述:
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。提示:1 <= nums.length <= 8-10 <= nums[i] <= 10
class Solution {
private int[] nums;
private boolean[] used;
private List<List<Integer>> result;
private List<Integer> temp;
private int len;
// 该变量作为起始位置(用于去除重复路径)
public List<List<Integer>> permuteUnique(int[] nums) {
// 初始化
this.nums = nums;
this.len = nums.length;
this.used = new boolean[len];
this.result = new ArrayList<List<Integer>>();
this.temp = new ArrayList<Integer>();
Arrays.sort(this.nums); // 排序:用于去重
DFS(0); // 第一个参数为已经遍历的元素个数 第二个参数作为起始位置(用于去除重复路径)
return result;
}
private void DFS(int count){
if(count == this.len){
ArrayList<Integer> temp = new ArrayList<Integer>();
for(int i = 0 ; i<this.len ; i++) temp.add(this.temp.get(i));
result.add(temp);
return;
}
for(int i = 0 ; i<this.len ; i++){
if(i>0 && !used[i-1] && this.nums[i] == this.nums[i-1]) continue; // 去重关键
if(!used[i]){
used[i] = true;
temp.add(nums[i]);
DFS(count+1);
used[i] = false;
temp.remove(this.temp.size() - 1);
}
}
}
}
主要难点是如果去重,即在该题的基础上添加两行语句即可,读者可以自己在草稿纸上模拟,这里简单地说明一下,首先经过排序后的数组,因为遍历到相同的元素段时,则会将第一次的会加入result数组中,其余的相同元素会因为continue跳过,故最终不会加入result数组中。