Combination Sum

解题思路:


从第i个candidate开始,有k个选择(要保证remain=target-candidate[i]*k>=0) 分别递归下去,一开始我以为可以用备忘录方法存储已经算出的值,后来发现不行,为什么?因为每次算的即使同样的值,用到的candidate也不一样,因此不算是同样的子问题.比如5可以表示为2 2 1 也可以表示为 2 3 不能认为是同一个子问题.


解题代码:


public class Solution {
     public List<List<Integer>> combinationSum(int[] candidates, int target) {
	       Arrays.sort(candidates);
	       this.candidates=candidates;
	       return combine(candidates.length-1,target);
	    	
	       
	    }
	public List<List<Integer>> combine(int k,int target)
	 {
		
	        if(k==0)
	        {
	        	if(target%candidates[0]==0)
	        	{
	        		List<List<Integer>>results=new ArrayList<List<Integer>>();
	        		List<Integer> ele=new ArrayList<Integer>();
	        		for(int i=0;i<target/candidates[0];i++)ele.add(candidates[0]);
	        		results.add(ele);
	        		
	        		return results;
	        	}else 
	        	{
	        		List<List<Integer>>results=new ArrayList<List<Integer>>();
	        		return results;
	        		
	        	}
	        }
	        if(target==0)
	        {
	        	List<List<Integer>>results=new ArrayList<List<Integer>>();
        		results.add(new ArrayList<Integer>());
        		
        		return results;
	        }
	        
	        List<List<Integer>>results=new ArrayList<List<Integer>>();
	        for(int i=target/candidates[k];i>=0;i--)
	        {
	        	int remain=target-candidates[k]*i;
	        	List<List<Integer>> sub_list=combine(k-1,remain);
	        	if(sub_list.isEmpty())continue;
	        	for(List<Integer> sub:sub_list)
                {
	        		for(int j=0;j<i;j++)
	        			sub.add(candidates[k]);
                    results.add(sub);
                }  	
	        }
	    
	        return results;
	 }
	  
	    private int[] candidates;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值