LeetCode78 SubSets

LeetCode78 SubSets

问题描述

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

简单分析

这道题和上一道题LeetCode77 Combinations很相似,这道题是求一个集合的子集,其实也就是一些组合加上其他的集合。
那么怎么修改前面的代码就可以实现呢。

很简单,在进入下一层递归的时候,就把当前的集合添加到结果集中。
比如
[1,2,3]以1开始的子集。

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

思路就是上面的思路,下面看代码。。

代码入下


public List<List<Integer>> subsets(int[] nums) {
    result.add(new ArrayList<>());
    if(nums==null||nums.length<1){
        return  result;
    }
    help(new ArrayList<>(),0,0,nums);
    return result;
}
List<List<Integer>> result = new ArrayList<>();
private void help(List<Integer> list,int from,int l,int[] nums){
    if(l==nums.length){
        return;
    }else {

        for (int i = from; i < nums.length; i++) {
            list.add(nums[i]);
            result.add(new ArrayList<>(list));
            help(list,i+1,l+1,nums);
            list.remove(list.size()-1);
        }
    }
}

LeetCode学习笔记持续更新

GitHub地址 https://github.com/yanqinghe/leetcode

CSDN博客地址 http://blog.csdn.net/yanqinghe123/article/category/7176678

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值