# [Lintcode] 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.

Example

Given candidate set [10,1,6,7,2,1,5] and target 8,

A solution set is:

[
[1,7],
[1,2,5],
[2,6],
[1,1,6]
]

public class Solution {
/**
* @param num: Given the candidate numbers
* @param target: Given the target number
* @return: All the combinations that sum to target
*/
public List<List<Integer>> combinationSum2(int[] num, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Arrays.sort(num);

helper(res, new ArrayList<Integer>(), num, target, 0);
return res;
}

void helper(List<List<Integer>> res, List<Integer> list, int[] num, int target, int index) {
if(target == 0) {
return;
}

if(index >= num.length || target < 0) return;

for(int i = index; i < num.length; i++) {
helper(res, list, num, target - num[i], i + 1);//i + 1 instead of index + 1
while(i + 1 < num.length && num[i] == num[i + 1]) i += 1;//在helper之后去重
//如果在helper之前去重的话，会漏掉结果集中存在重复元素的情况
// 1 1 2 5 6 7 10 -> 1 1 2 OK 在helper前去重漏掉的情况
// 1 1 2 5 6 7 10 -> 1 2 5, 1 2 5 KO 需要去重的情况
list.remove(list.size() - 1);
}
}
}



#### Combination Sum 系列问题（leetcode dfs回溯，动归）由浅入深DFS

2016-09-28 09:14:36

#### [leetcode]40. Combination Sum II ,python实现【medium难度】

2016-06-16 17:37:04

#### LeetCode40：Combination Sum II

2015-07-06 21:17:58

#### Combination Sum II -- LeetCode

2014-03-13 04:30:39

#### 40. Combination Sum II

2015-07-22 09:20:00

#### (Java)LeetCode-40. Combination Sum II

2016-08-11 23:33:03

#### 回溯法——combination-sum、combination-sum-ii

2016-05-31 13:27:11

#### 【LeetCode】Combination Sum I & II 解题报告

2014-12-16 11:06:12

#### Leetcode 39 Combination Sum & 40 Combination Sum II & 216 Combination Sum III & 377 Combination V

2016-07-26 13:38:06

#### LeetCode40 Combination Sum II 解析

2017-04-06 22:20:53