【全排列 II&&子集】
算法:回溯算法
力扣 47. 全排列 II
给定一个可包含重复数字的序列 nums
,按任意顺序 返回所有不重复的全排列。
示例 1:
输入:nums = [1,1,2]
输出:
[[1,1,2],
[1,2,1],
[2,1,1]]
示例 2:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
来源:力扣(LeetCode)
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
int len=nums.length;
boolean[] used=new boolean[len];//判断是否使用,状态量
List<List<Integer>> res=new ArrayList<>();
Deque<Integer> path=new ArrayDeque<>();//栈,保存叶子节点结果
dfs(nums,0,path,len,used,res);
return res;
}
private void dfs(int[] nums, int depth, Deque<Integer> path, int len, boolean[] used, List<List<Integer>> res) {
if(depth==len){//递归终止条件
res.add(new ArrayList<>(path));
return;
}
for(int i=0;i<len;i++){
if(used[i])//使用过的元素跳过
continue;
//剪枝
else if(i!=0&&nums[i]==nums[i-1]&&used[i-1]){
//i!=0,防止i-1越界
// nums[i]==nums[i-1],当前值与上一个一样,继续选择就会重复
//used[i-1],上一个元素已经被使用过
continue;
}
//没有使用过的元素加入
path.addLast(nums[i]);
used[i]=true;
dfs(nums,depth+1,path,len,used,res);
//回撤
path.removeLast();
used[i]=false;
}
}
}
注意传递的是depth+1,for循环的i起始值是0(找树的叶子节点)
力扣 78. 子集
给你一个整数数组 nums
,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
来源:力扣(LeetCode)
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res=new ArrayList<>();
int len=nums.length;
Deque<Integer> path=new ArrayDeque<>();//栈
dfs(nums,len,path,res,0);
return res;
}
private void dfs(int[] nums, int len, Deque<Integer> path, List<List<Integer>> res, int depth) {
res.add(new ArrayList<>(path));//为了添加空集,add写在最前面
if(depth==len)//递归终止条件
return;
for(int i=depth;i<len;i++){
path.addLast(nums[i]);//入栈
dfs(nums,len,path,res,i+1);
path.removeLast();//回撤
}
}
}
注意传递的是i+1,for循环的i起始值是depth(找树的所有节点)
for循环条件怎么写?参考链接:https://leetcode-cn.com/problems/permutations/solution/hui-su-suan-fa-python-dai-ma-java-dai-ma-by-liweiw/