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 (a1a2, … , 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]

 

 1 public class Solution {
 2     ArrayList<ArrayList<Integer>> result = null;
 3     public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
 4         // Note: The Solution object is instantiated only once and is reused by each test case.
 5         Arrays.sort(num);
 6         result = new ArrayList<ArrayList<Integer>>();
 7         getSolution(new ArrayList<Integer>(), target, num, 0);
 8         return result;
 9     }
10     public void getSolution(ArrayList<Integer> row, int target, int[] num, int pos){
11         int i = pos;
12         int per = -1;
13         if(target == 0){
14             result.add(row);
15         }
16         while(i < num.length && num[i] <= target){
17             if(per != num[i]){
18                 per = num[i];
19                 row.add(num[i]);
20                 target -= num[i];
21                 int tmp = num[i];
23 getSolution(new ArrayList<Integer>(row), target, num, i + 1); 24 row.remove(row.size() - 1);
26 target += num[i]; 27 } 28 i ++; 29 } 30 } 31 }

 第三遍:

test case:

Input: [1,1], 1
Output: [[1],[1]]
Expected: [[1]]

结果相同如何处理。

 1 public class Solution {
 2     public List<List<Integer>> combinationSum2(int[] candidates, int target) {
 3         Arrays.sort(candidates);
 4         List<List<Integer>> result = new ArrayList<List<Integer>>();
 5         findElement(candidates, 0, candidates.length, result, new ArrayList<Integer>(), target);
 6         return result;
 7     }
 8     
 9     public void findElement(int[] arr, int start, int end, List<List<Integer>> result, ArrayList<Integer> row, int tar){
10         if(tar == 0) result.add(row);
11         for(int i = start; i < end; i ++){
12             if((i == start || arr[i] != arr[i - 1]) && arr[i] <= tar){
13                 ArrayList<Integer> rown = new ArrayList<Integer> (row);
14                 rown.add(arr[i]);
15                 findElement(arr, i + 1, end, result, rown, tar - arr[i]);
16             }
17         }
18     }
19 }
(i == start || arr[i] != arr[i - 1]) 保证了在同一层里不会选取一样的数字。

posted on 2013-10-16 03:31  Step-BY-Step  阅读(194)  评论(0编辑  收藏  举报

导航