40. Combination Sum II(midum, backtrack, 重要)

时间:2023-03-09 04:20:42
40. Combination Sum II(midum, backtrack, 重要)

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

这题用到 backtrack 方法, 需去重.

e.g.

A = [1 1 2 5 6 7 10], target = 8

正确输出应该是:

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

难点在去重条件:
* 我写的,错误: `if(i >= 1 && A[i] == A[i - 1]) continue;`
- 错误输出: `[[1,2,5],[1,7],[2,6]]`
* 人家写的,正确: `if ((i >= 1) && (A[i] == A[i - 1]) && (i > start)) continue;`

差别就是 i > start 条件,挺不容易的想出来的.

自己想法,自个代码(被人家修正^^):

// backtrack
// A = [1 1 2 5 6 7 10]
vector<vector<int>> combinationSum2(vector<int>& A, int ta) {
sort(A.begin(), A.end());
vector < vector<int> > res;
vector<int> temp;
backtrack(A, res, temp, ta, 0);
return res;
} void backtrack(vector<int>& A, vector<vector<int> >& res, vector<int> temp,
int remain, int start) {
if (remain < 0)
return;
else if (remain == 0)
res.push_back(temp);
else {
for (int i = start; i < A.size(); i++) { // not correct: if(A[i] == A[i - 1] && i >= 1) continue;
// (i > start) is hard think, but important. if ((i >= 1) && (A[i] == A[i - 1]) && (i > start))
continue; // check duplicate combination temp.push_back(A[i]);
backtrack(A, res, temp, remain - A[i], i + 1); // i + 1, next element
temp.pop_back();
}
}
}