首页 > 其他 > 详细

[Leetcode] Combination Sum

时间:2015-08-12 21:34:42      阅读:98      评论:0      收藏:0      [点我收藏+]

由于每个元素我可以出现的次数没有限制,我们可以在使用某个元素的时候进行计算一下最多的个数,进行枚举。

同样的道理,在每一层递归只考虑一个元素,并且在当前sum大于目标sum的时候进行剪枝。

 

 1 import java.util.*;
 2 
 3 public class Solution {
 4     public void dp(int[] candidates, int index, int target,List<List<Integer>> lists,
 5     List<Integer> tmplist, int tmpsum){
 6         if(tmpsum==target) {
 7             List<Integer> l = new LinkedList<Integer>();
 8             l.addAll(tmplist);
 9             lists.add(l);
10             return;
11         }
12         if(tmpsum>target||index==candidates.length) return;
13         int maxnum=(target-tmpsum)/candidates[index];
14         for(int i=0;i<maxnum;i++){
15             tmplist.add(candidates[index]);
16             dp(candidates,index+1,target,lists,tmplist,tmpsum+candidates[index]*(i+1));
17         }
18         for(int i=0;i<maxnum;i++){
19             tmplist.remove(tmplist.size()-1);
20         }
21         dp(candidates,index+1,target,lists,tmplist,tmpsum);
22     }
23     public List<List<Integer>> combinationSum(int[] candidates, int target) {
24         // if the candidates are not sorted ,then we need to sort each conditioned 
25         // tmplist. Because it need the tmplist should be sorted.
26         Arrays.sort(candidates);
27         List<List<Integer>> lists =new LinkedList<List<Integer>> ();
28         List<Integer> tmplist = new LinkedList<Integer>();
29         dp(candidates,0,target,lists,tmplist,0);
30         return lists;
31     }
32 }

 

[Leetcode] Combination Sum

原文:http://www.cnblogs.com/deepblueme/p/4725534.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!