Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
找出所有长度0-n个的子元素集合:
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(nums==null) {
return res;
}
for(int i=0;i<=nums.length;i++) {
setRes(i,res,new ArrayList<>(),nums,0);
}
return res;
}
public void setRes(int num,List<List<Integer>> res,List<Integer> tmpRes,int[] nums,int begin) {
if(num==0) {
res.add(new ArrayList<>(tmpRes));
return;
}
for(int i=begin;i<nums.length;i++) {
tmpRes.add(nums[i]);
setRes(num-1,res,tmpRes,nums,i+1);
tmpRes.remove(tmpRes.size()-1);
}
}
}