题目:
代码(首刷看解析 2024年2月1日):
class Solution {
public:vector<vector<int>> res;vector<int> path;void backtracking(vector<int>& candidates, int target, int startIndex, vector<bool>& used) {if (target == 0) {res.push_back(path);return;}for (int i = startIndex; i < candidates.size(); ++i) {if (i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]) continue;target -= candidates[i];if (target < 0) return;path.push_back(candidates[i]);used[i] = true;backtracking(candidates, target, i + 1, used);used[i] = false;path.pop_back();target += candidates[i];}return;}vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {vector<bool> used(candidates.size(),0);//used用来辨别使用过的元素sort(candidates.begin(), candidates.end());backtracking(candidates, target, 0, used);return res;}
};