首页 > 代码库 > LeetCode Combination Sum II

LeetCode 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 toT.

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] 

 

 1 public class Solution { 2     List<List<Integer>> result; 3     public List<List<Integer>> combinationSum2(int[] num, int target) { 4         result = new ArrayList<List<Integer>>(); 5         List<Integer> list = new ArrayList<Integer>(); 6         Arrays.sort(num); 7         combination(num, 0, list, target); 8         return result; 9     }10     11         void combination(int[] num,int index,List<Integer> curr,int target) {12         if (target == 0) {13             result.add(new ArrayList<Integer>(curr));14 15         } else {16             for (int i = index; i < num.length; i++) {17                 if (i != index && num[i] == num[i - 1]) {18                     continue;19                 }20                 if (target >= num[i]) {21                     curr.add(num[i]);22                     combination(num, i + 1, curr, target - num[i]);23                     curr.remove(curr.size() - 1);24                 }25             }26         }27 28     }29     30 }

 

LeetCode Combination Sum II