# 组合总和

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

示例 1:

输入:candidates = [2,3,6,7], target = 7,
输出:
[[7],[2,2,3]]

示例 2:

输入:candidates = [2,3,5], target = 8,
输出:
[[2,2,2,2],[2,3,3],[3,5]]

 

提示:

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp int main() { Solution sol; vector> res; vector candidates = {2, 3, 6, 7}; int target = 7; res = sol.combinationSum(candidates, target); for (auto i : res) { for (auto j : i) cout << j << " "; cout << endl; } return 0; } ``` ## 答案 ```cpp class Solution { public: vector> combinationSum(vector &candidates, int target) { set> res; vector temp; sort(candidates.begin(), candidates.end()); fun(candidates, target, 0, temp, res); vector> result; for (auto mem : res) { result.push_back(mem); } return result; } void fun(const vector &candidates, int target, int index, vector &temp, set> &res) { if (target < 0) return; if (target == 0) { res.insert(temp); return; } while (index < candidates.size()) { temp.push_back(candidates[index]); fun(candidates, target - candidates[index], index + 1, temp, res); temp.pop_back(); ++index; } } }; ``` ## 选项 ### A ```cpp class Solution { public: vector> combinationSum(vector &candidates, int target) { vector> res; dfs(candidates, 0, target, res); return res; } private: vector stack; void dfs(vector &candidates, int start, int target, vector> &res) { if (target < 0) { return; } else if (target == 0) { res.push_back(stack); } else { for (int i = start; i < candidates.size(); i++) { stack.push_back(candidates[i]); dfs(candidates, i, target - candidates[i], res); stack.pop_back(); } } } }; ``` ### B ```cpp class Solution { public: void compute(int start, int target, vector &tmp, vector &candidates, vector> &ans) { int n = candidates.size(); for (int i = start; i < n; i++) { if (target > 0) { tmp.push_back(candidates[i]); compute(i, target - candidates[i], tmp, candidates, ans); tmp.pop_back(); } else if (target < 0) return; else { ans.push_back(tmp); return; } } } vector> combinationSum(vector &candidates, int target) { vector> ans; vector tmp; int v; sort(candidates.begin(), candidates.end()); compute(0, target, tmp, candidates, ans); return ans; } }; ``` ### C ```cpp class Solution { private: vector> res; vector ans; public: vector> combinationSum(vector &candidates, int target) { sort(candidates.begin(), candidates.end()); int left = 0, right = 0; for (; right < candidates.size() && candidates[right] <= target; right++) ; backtrack(candidates, left, right == candidates.size() ? right - 1 : right, target); return res; } private: void backtrack(vector &candidates, int left, int right, int target) { if (target < 0) return; if (!target) { res.push_back(ans); return; } for (int i = left; i <= right && candidates[i] <= target; i++) { ans.push_back(candidates[i]); backtrack(candidates, i, right, target - candidates[i]); ans.pop_back(); } } }; ```