### 主要收获

ROCK the Backtracking!

### 题目

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. 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]
]


### 直接标准回溯算法 $O(2^n)$

backtracking(temp, preRemain, candidates, i+1, target, result); // 注意这里的i+1


if (i != start && candidates[i] == candidates[i-1]) { continue; } // eliminates duplicates


#### 代码

public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result = new ArrayList<>();
backtracking(new ArrayList<Integer>(), target, candidates, 0, target, result);
return result;
}
public void backtracking(List<Integer> temp, int remain, int[] candidates, int start, int target, List<List<Integer>> result) {
if (remain == 0) {
return;
}
for (int i = start; i < candidates.length; i++) {
if (i != start && candidates[i] == candidates[i-1]) { continue; } // eliminates duplicates
int preRemain = remain - candidates[i];
if (preRemain < 0) { break; } // 剪枝