DFS和回溯专题:全排列 II
题目描述
代码纯享版
class Solution {
public List<List<Integer>> list_all = new ArrayList();
public List<Integer> list = new ArrayList();
public int[] res;
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
res = new int[nums.length];
backtrack(nums);
return list_all;
}
void backtrack(int[] nums){
if(list.size() == nums.length){
list_all.add(new ArrayList(list));
return;
}
for(int i = 0; i < nums.length; i++){
if(i > 0 && nums[i] == nums[i - 1] && res[i - 1] == 0){
continue;
}
if(res[i] == 0){
list.add(nums[i]);
res[i] = 1;
backtrack(nums);
res[i] = 0;
list.remove(list.size() - 1);
}
}
}
}
代码逐行解析版
class Solution {
public List<List<Integer>> list_all = new ArrayList();
public List<Integer> list = new ArrayList();
public int[] res;
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
res = new int[nums.length];
backtrack(nums);
return list_all;
}
void backtrack(int[] nums){
if(list.size() == nums.length){
list_all.add(new ArrayList(list));
return;
}
for(int i = 0; i < nums.length; i++){
if(i > 0 && nums[i] == nums[i - 1] && res[i - 1] == 0){
continue;
}
if(res[i] == 0){
list.add(nums[i]);
res[i] = 1;
backtrack(nums);
res[i] = 0;
list.remove(list.size() - 1);
}
}
}
}