LeetCode - Subsets I && II

https://leetcode.com/problems/subsets/

这道题比较典型,一般需要all, every之类所有结果的,都可以用递归做,因为题目要求结果要升序,所以在做之前对数组排序,并且在做之前把空集放进去。

注意递归调用helper那行,下一个start不应该是start+1,而是i+1

    public List<List<Integer>> subsets(int[] S) {
        List<List<Integer>> rst = new LinkedList<List<Integer>>();
        if(S==null || S.length==0) return rst;
        List<Integer> sol = new LinkedList<Integer>();
        Arrays.sort(S);   // to ensure ascending order in the result list
        rst.add(sol);
        helper(S, 0, rst, sol);
        return rst;
    }
    public void helper(int[] S, int start, List<List<Integer>> rst, List<Integer> sol){
        for(int i=start; i<S.length; i++){
            sol.add(S[i]);
            rst.add(new LinkedList<Integer>(sol));
            helper(S, i+1, rst, sol); //!!!should be i+1, instead of start+1 here
            sol.remove(sol.size()-1);
        }
    }

附一个不用递归的方法:

Given a set S of n distinct integers, there is a relation between Sn and Sn-1. The subset of Sn-1 is the union of {subset of Sn-1} and {each element in Sn-1 + one more element}. Therefore, a Java solution can be quickly formalized.

http://www.programcreek.com/2013/01/leetcode-subsets-java/

一亩三分地上对这道题时间复杂度分析:

http://www.1point3acres.com/bbs/thread-117602-1-1.html

时间复杂度分析看得不是很懂,todo:把在做完combination之后把这篇分析看懂!


Subsets II

https://leetcode.com/problems/subsets-ii/

跟Subsets I 基本完全一样,只需要在循环到下一个数时,略掉重复数就可以避免重复子集,注意,进入下一层递归时,是不需要略掉重复数的,因为一个子集里可以有重复元素。

public List<List<Integer>> subsetsWithDup(int[] S) {
        List<List<Integer>> rst = new LinkedList<List<Integer>>();
        if(S==null || S.length==0) return rst;
        List<Integer> sol = new LinkedList<Integer>();
        Arrays.sort(S);   // to ensure ascending order in the result list
        rst.add(sol);
        helper(S, 0, rst, sol);
        return rst;
    }
    public void helper(int[] S, int start, List<List<Integer>> rst, List<Integer> sol){
        for(int i=start; i<S.length; i++){
            sol.add(S[i]);
            rst.add(new LinkedList<Integer>(sol));
            helper(S, i+1, rst, sol); //!!!should be i+1, instead of start+1 here
            sol.remove(sol.size()-1);
            while((i+1)<S.length && S[i+1]==S[i]) i++;
        }
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值