[leet code] Subsets

Given a set of distinct integers, S, 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 S = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]
==================

Analysis:

First of all, I don't think this problem is easy (many blogs mentioned that it is a basic recursion problem, maybe it is a sample in the text book, but it's not my case).  This problem can be simplified to given an array, then find out all the subsets in certain length.  For example, given array [1,2,3,4,5], find out all the subset in the length of 3 ([1,2,3] [1,2,4] [1,2,5] [1,3,4] [1,3,5] ...).  After we have this solution, we can use an iteration to do subset length=0,1,2,3,4,5 to solve our "Subsets" problem.

Regarding to the simplified problem, we can use recursive approach, process of which as below:

1. Choose the 1st number from given array.

2. Use recursive call to choose length-1 numbers from array excluding the numbers that have been chosen.

Exit of the recursive call: when length of the constructing array reach the required subset length, then add it to the result set and return.

public class Solution {
    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        // for test case
        Arrays.sort(S);
        
        // length a subset
        for(int i=0; i<=S.length; i++){
            ArrayList<Integer> subResult = new ArrayList<Integer>();
            helper(S, result, subResult, i, 0);
        }
        return result;
    }
    
    public void helper(int[] S, ArrayList<ArrayList<Integer>> result, ArrayList<Integer> subResult, int length, int elementNum){
        if(subResult.size() == length){
            result.add(new ArrayList<Integer>(subResult));
            return;
        }
        
        for(int i=elementNum; i<S.length; i++){ // for each element in S
            subResult.add(S[i]); // choose the 1st number for subset
            helper(S, result, subResult, length, i+1); // choose the remaining numbers for subset
            subResult.remove(subResult.size()-1); // remove the chosen 1st number, and rechoose it in the next iteration
        }
    }
}




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值