Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

 

For example, given candidate set 10,1,2,7,6,1,5 and target 8
A solution set is: 
[1, 7] 
[1, 2, 5] 
[2, 6] 
[1, 1, 6] 

这道题只需在Combination Sum稍微改一下就行了

 1 import java.util.ArrayList;
 2 import java.util.Arrays;
 3 import java.util.List;
 4 import org.w3c.dom.CDATASection;
 5 
 6 public class Solution {
 7     public List<List<Integer>> combinationSum2(int[] num, int target) {
 8         Arrays.sort(num);
 9         List<List<Integer>> result = new ArrayList<List<Integer>>();
10         getResult(result, new ArrayList<Integer>(), num, target, 0);
11         
12         return result;
13     }
14     
15     private void getResult(List<List<Integer>> result, List<Integer> cur, int candidates[], int target, int start){
16         if(target > 0){
17             for(int i = start; i < candidates.length && target >= candidates[i]; i++){
18                 cur.add(candidates[i]);
19                 getResult(result, cur, candidates, target - candidates[i], i + 1);
20                 cur.remove(cur.size() - 1);
21                 
22             }//for
23         }//if
24         else if(target == 0 && !result.contains(cur)){            
25             result.add(new ArrayList<Integer>(cur));
26             
27         }//else if
28     }
29     
30 }

 

posted on 2015-01-22 11:06  luckygxf  阅读(152)  评论(0编辑  收藏  举报

导航