78.Subsets leetcode java

题目:

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],
  []
]
给定一个不重复整数的集合,返回所有可能的子集,解集不能包含重复的子集

思路:

看到all possible subsets是典型的DFS,套用排列组合模板

class Solution {
    public List> subsets(int[] nums) {
        List> res = new ArrayList>();
        List subset = new ArrayList();
        if(nums.length==0){
            return res;
        }
        Arrays.sort(nums);
        helper(subset,nums,0,res);
        return res;
    }
    public void helper(List subset,int[] nums,int pos,List> res){//找到所有以subset开头的所有子集
        res.add(new ArrayList(subset));//因为java传的是引用,如果直接把subsetadd进去,之后subset变化后add进去的对象也会发生变化,这里相当于拍个快照add进去
        for(int i=pos;i


你可能感兴趣的:(78.Subsets leetcode java)