题目来源:https://leetcode.cn/problems/combination-sum-ii/description/
C++题解: 这道题的难点在于解集中不能包含重复的组合。如果用set去重会造成超时,所以只能在单层递归逻辑中处理。通过识别下一个数与当前数是否相同,来修改下一次回溯的遍历起始值。
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void backtracking(vector<int> candidates, int target, int startInd, int sum) {
if(sum > target) return;
else if(sum == target) {res.push_back(path); return;}
for(int i = startInd; i < candidates.size(); i++) {
if(sum + candidates[i] > target) break;
path.push_back(candidates[i]);
backtracking(candidates, target, i + 1, sum + candidates[i]);
path.pop_back();
while(i + 1 < candidates.size() && candidates[i] == candidates[i+1]) i++;
}
return;
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
if(candidates[0] > target) return res;
backtracking(candidates, target, 0, 0);
return res;
}
};