给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
代码:
方法1
class Solution {
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
List<Integer> temp = new ArrayList<>();
backtrack(temp,nums,0);
return ans;
}
public void backtrack(List<Integer> temp,int[] nums,int count){
//如果count等于数组长度,则返回。否则只是把temp添加
if(count == nums.length){
ans.add(new ArrayList(temp));
return;
}else {
ans.add(new ArrayList(temp));
}
for (int i=count;i<nums.length;i++){
temp.add(nums[i]);
backtrack(temp,nums,++count);
temp.remove(temp.size()-1);
}
}
}
方法2
public List<List<Integer>> subsets(int[] nums) {
List<Integer> temp=new ArrayList<>();
dfs(nums,temp,0);
res.add(new ArrayList<>());
return res;
}
public List<List<Integer>> res=new ArrayList<>();
public void dfs(int []nums,List<Integer> temp,int len){
for(int i=len;i<nums.length;i++){
temp.add(nums[i]);
res.add(new ArrayList<>(temp));
dfs(nums,temp,i+1);
temp.remove(temp.size()-1);
}
}
本文介绍了一种生成给定整数数组所有可能子集(幂集)的方法,通过两种递归方式实现,确保解集中不包含重复子集。示例展示了输入数组[1,2,3]的所有子集。
804

被折叠的 条评论
为什么被折叠?



