leetcode 78 Subsets ----- java

Given a set of distinct integers, nums, return all possible subsets.

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],
  []
]

 上一道题的延伸,给一个集合,求出所有他的子集。

 略微修改,就可以得到答案。注意不要少了空集。

public class Solution {

    List<List<Integer>> res = new ArrayList<>();
    int[] num;
    int len;

    public List<List<Integer>> subsets(int[] nums) {
        len = nums.length;
        num = nums;
        res.add(new ArrayList<>());
        sub(0,new ArrayList<>() );

        return res;
    }

    public void sub(int start,List<Integer> ans){

        for( int i = start;i<len;i++){
            ans.add(num[i]);
            res.add(new ArrayList<Integer>(ans));
            sub(i+1,ans);
            ans.remove(ans.size()-1);
        }
        return ;
    }
    
}
 
原文地址:https://www.cnblogs.com/xiaoba1203/p/5967031.html