Leetcode 之 Subsets

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


最先想到的思路就是从空集开始,依次添加:1位数,2位数。。。
[] || [1], [2], [3] || [1,2], [1,3], [2,3] || [1,2,3]
[1,2]和[1,3] 是由1生成的,[2,3]是由2生成的
所以每次只要设置两个下标,分别记录当前所在的区段(1位数还是2位数还是3位数。。即可)
每次在这个区段循环,找每个元素的最后一位,给最后一位添加比他大的数字,加到最终的list列表中,count指针加1。每轮循环结束都把start和end后移。一直到list列表最后一个元素的大小与nums数组长度相同终止循环。

     List<List<Integer>> list = new ArrayList<List<Integer>>();

     public List<List<Integer>> subsets(int[] nums) {    
         ArrayList<Integer> l = new ArrayList<Integer>();
         Arrays.sort(nums);
         list.add(new ArrayList<Integer>());
         for(int i = 0;i < nums.length;i++){
             ArrayList<Integer> tempList = new ArrayList<Integer>();
             tempList.add(nums[i]);
             list.add(tempList);
         }
         add(1,list.size() - 1,nums);
         return list;
     }

     public void add(int start,int end,int[] nums){

         while(list.get(list.size() - 1).size() < nums.length){
             int count = 0;
             for(int i = start; i <= end;i++){
                ArrayList<Integer> lastList = (ArrayList<Integer>) list.get(i);

                int lastVal = lastList.get(lastList.size() - 1);
                for(int j = 0;j < nums.length;j++){
                    if(nums[j] > lastVal){
                        ArrayList<Integer> newList = new ArrayList<Integer>(lastList);
                        newList.add(nums[j]);
                        list.add(newList);
                        count++;
                    }
                }

            }
            start = end + 1;
            end += count;

         }
     }

10 / 10 test cases passed.
Status: Accepted
Runtime: 316 ms

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值