码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Combination Sum II

时间:2015-08-12 21:33:47      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

实际上这里的道理和Combination Sum是一样的,只是对于每个元素的次数我们不需要在每次递归的时候进行计算上限,因为题目限制了最多的出现次数。

其他类似。

 1 import java.util.*;
 2 
 3 public class Solution {
 4     private void dp(Vector<Integer> num, Vector<Integer> count,int index, int target, int tmpsum, 
 5     List<Integer> tmplist,List<List<Integer> > lists){
 6         if(tmpsum==target){
 7             List<Integer> l = new LinkedList<Integer>();
 8             l.addAll(tmplist);
 9             lists.add(l);
10             return;
11         }
12         if(index==num.size()||tmpsum>target) return;
13         int tmpcount=count.get(index);
14         int number=num.get(index);
15         for(int i=0;i<tmpcount;i++){
16             tmplist.add(number);
17             dp(num,count,index+1,target,tmpsum+(i+1)*number,tmplist,lists);
18         }
19         //because there is only one tmplist, when all the cases which contain number 
20         //has been tried, we try the one which ignore it.
21         for(int i=0;i<tmpcount;i++){
22             tmplist.remove(tmplist.size()-1);
23         }
24         dp(num,count,index+1,target,tmpsum,tmplist,lists);
25     }
26     public List<List<Integer>> combinationSum2(int[] candidates, int target) {
27         Arrays.sort(candidates);
28         /////the code below is to statistic the unique numbers and the number 
29         /////of each of them
30         Vector<Integer> num =new Vector<Integer>();
31         Vector<Integer> count =new Vector<Integer>();
32         int pre=candidates[0];
33         int tmpcount=1;
34         for(int i=1;i<candidates.length;i++){
35             if(candidates[i]==pre){
36                 tmpcount++;
37             }else{
38                 num.add(pre);
39                 count.add(tmpcount);
40                 pre=candidates[i];
41                 tmpcount=1;
42             }
43         }
44         num.add(pre);
45         count.add(tmpcount);
46         //to call the method above
47         List<Integer> tmplist =new LinkedList<Integer>();
48         List<List<Integer> > lists =new LinkedList<List<Integer> >();
49         dp(num,count,0,target,0,tmplist,lists);
50         return lists;
51     }
52 }

 

[Leetcode] Combination Sum II

标签:

原文地址:http://www.cnblogs.com/deepblueme/p/4725538.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!