subsets(子集)

时间:2023-12-29 17:17:08

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

求给定数组的元素的子集。

这题跟组合combination、全排列都有点像。列举所有情况,所以可以使用回溯。

因为没有重复元素,所以不需要排列。

依次遍历,并从后面的元素中继续选择作为集合元素。

条件是:只要集合list中的元素长度小于等于数组长度,就添加,表示满足要求,是一个子集。

代码如下:

class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res=new ArrayList<List<Integer>>();
if(nums==null||nums.length==0) return res;
helper(res,new ArrayList<Integer>(),nums,0);
return res;
} public void helper(List<List<Integer>> res,List<Integer> list,int[] nums,int index){
if(list.size()<=nums.length){
res.add(new ArrayList<Integer>(list));
}
for(int i=index;i<nums.length;i++){
list.add(nums[i]);
helper(res,list,nums,i+1);
list.remove(list.size()-1);
}
}
}