diff --git a/include/s0039_combination_sum.hpp b/include/s0039_combination_sum.hpp index 45b83f4..f16dd73 100644 --- a/include/s0039_combination_sum.hpp +++ b/include/s0039_combination_sum.hpp @@ -2,7 +2,6 @@ #define S0039_COMBINATION_SUM_HPP #include -#include #include using namespace std; @@ -10,8 +9,6 @@ using namespace std; class S0039 { public: vector> combinationSum(vector& candidates, int target); - void dfs(vector& candidates, int target, vector>& ans, - vector& combine, int idx); }; #endif diff --git a/notes/src/combinations.md b/notes/src/combinations.md index db26057..c51c7a3 100644 --- a/notes/src/combinations.md +++ b/notes/src/combinations.md @@ -69,6 +69,6 @@ void combineDFS(int n, int k, int begin, vector &path, } ``` +## [39. 组合总和](https://leetcode.cn/problems/combination-sum/) + ## [216. 组合总和 III](https://leetcode.cn/problems/combination-sum-iii/) - - diff --git a/src/s0039_combination_sum.cpp b/src/s0039_combination_sum.cpp index f05a703..a951bc7 100644 --- a/src/s0039_combination_sum.cpp +++ b/src/s0039_combination_sum.cpp @@ -1,27 +1,31 @@ #include "s0039_combination_sum.hpp" -void S0039::dfs(vector& candidates, int target, vector>& ans, - vector& combine, int idx) { - if (idx == candidates.size()) { +void combinationSumDFS(vector &candidates, int target, int startIndex, + vector &path, int sum, + vector> &result) { + // 结束条件:总和等于 target 。不存在总和大于 target 的情况,因为已经被剪枝了 + if (sum == target) { + result.push_back(path); return; } - if (target == 0) { - ans.emplace_back(combine); - return; - } - // 直接跳过 - dfs(candidates, target, ans, combine, idx + 1); - // 选择当前数 - if (target - candidates[idx] >= 0) { - combine.emplace_back(candidates[idx]); - dfs(candidates, target - candidates[idx], ans, combine, idx); - combine.pop_back(); + + // 开始迭代 + int size = candidates.size(); + for (int i = startIndex; i < size; ++i) { + // 剪枝,当现在节点的 sum 已经超过了 target,就没必要继续迭代了 + if (sum + candidates[i] > target) break; + path.push_back(candidates[i]); + combinationSumDFS(candidates, target, i, path, sum + candidates[i], result); + path.pop_back(); } } -vector> S0039::combinationSum(vector& candidates, int target) { - vector> ans; - vector combine; - dfs(candidates, target, ans, combine, 0); - return ans; +vector> S0039::combinationSum(vector &candidates, int target) { + // 对 candidates 进行升序排序,这是为了进行剪枝 + sort(candidates.begin(), candidates.end()); + // 初始化 + vector path{}; + vector> result{}; + combinationSumDFS(candidates, target, 0, path, 0, result); + return result; }