[Leetcode] Combination Sum II
实际上这里的道理和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 }