leetcode做题总结,题目Combinations 2012/04/18

像这种一般往下分的我首先想到的就是递归,因为好久没刷题了,不知道DP可不可以做

不过要注意的一个点是有时候会遇到List<List> 这种,由于List要具体到一个特定的List,所以在new的时候要用ArrayList<List>,里面的List不能直接具体到某个List.


public class Solution {
    public List<List<Integer>> compute(int i,int j, int k){
        if(k==1){
            List<List<Integer>> l = new ArrayList<List<Integer>>();
            ArrayList<Integer> l2= null;
            for(int m=i;m<=j;m++){
                l2=new ArrayList<Integer>();
                l2.add(m);
                l.add(l2);
            }
            return l;
        }
        List<List<Integer>> l = new ArrayList<List<Integer>>();
         List<List<Integer>> l2=null;
         List<Integer> tmp=null;
        for(int m=i;m<j-k+2;m++){
            l2=compute(m+1,j,k-1);
            for(int x=0;x<l2.size();x++){
                tmp=l2.get(x);
                tmp.add(0,m);
                l.add(tmp);
            }
        }
        return l;
        
    }
    
    
    public List<List<Integer>> combine(int n, int k) {
        return compute(1,n,k);
    }
}

Update 2015/08/28: 上面的解法很烂,这里是典型的回溯法


public class Solution {
    /**
     * @param n: Given the range of numbers
     * @param k: Given the numbers of combinations
     * @return: All the combinations of k numbers out of 1..n
     */
     
    public void compute(
        ArrayList<List<Integer>>res,
        ArrayList<Integer> tmp,
        int n,
        int k,
        int s){
        if (k == 0)
            res.add(new ArrayList<Integer>(tmp));
        for (int i = s; i <= n; i++){
            tmp.add(i);
            compute(res, tmp, n, k - 1, i + 1);
            tmp.remove(tmp.size() - 1);
        }
        
    }
    
    public List<List<Integer>> combine(int n, int k) {
		// write your code here
		ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
		ArrayList<Integer> tmp = new ArrayList<Integer>();
		compute(res, tmp, n, k, 1);
		return res;
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值