Leetcode 78. Subsets 子集 解题报告

1 解题思想

这道题需要求给定数组的子集,特别要求有:
1、必须是升序
2、不能出现重复的

所以做法其实也就是,首先排序,然后回溯。。和昨天那题一样,可以回去看一下。记得选择下一个的时候,别和当前的值重复就可以了。

2 原题

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

Note:
Elements in a subset must be in non-descending order.
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],
[]
]

3 AC解

public class Solution {
    /**
     * 原来这道题是不在乎顺序的。。我用的方式是我习惯的。。没亮点,所以用List了。。
     * 用bit位可也咯,用boolean数组代替也好。。。都可以。。看你习惯哪种了,反正没添加一个,都要遍历一次,心累
     * 
     * 对了,List是引用。。所以要重新创建一个新的对象才行哦。。。不然就挂了。。
     * */
    int[] nums;
    List<List<Integer>> result;
    public void find(int index,List<Integer> last){
        if(index>=nums.length)
            return ;
        ArrayList<Integer> item=new ArrayList<Integer>();
        item.addAll(last);
        item.add(nums[index]);
        result.add(item);
        find(index+1,last);
        find(index+1,item);


    }
    public List<List<Integer>> subsets(int[] nums) {
        Arrays.sort(nums);
        this.nums=nums;
        this.result=new ArrayList<List<Integer>>();
        int i=0;
        ArrayList<Integer> tmp=new ArrayList<Integer>();
        result.add(tmp);
        find(i,tmp);
        return result;


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值