This commit is contained in:
Sainnhe Park 2023-02-02 10:40:18 +08:00
parent 30d9599c39
commit f572d2c9e0
3 changed files with 25 additions and 24 deletions

View File

@ -2,7 +2,6 @@
#define S0039_COMBINATION_SUM_HPP #define S0039_COMBINATION_SUM_HPP
#include <algorithm> #include <algorithm>
#include <iterator>
#include <vector> #include <vector>
using namespace std; using namespace std;
@ -10,8 +9,6 @@ using namespace std;
class S0039 { class S0039 {
public: public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target); vector<vector<int>> combinationSum(vector<int>& candidates, int target);
void dfs(vector<int>& candidates, int target, vector<vector<int>>& ans,
vector<int>& combine, int idx);
}; };
#endif #endif

View File

@ -69,6 +69,6 @@ void combineDFS(int n, int k, int begin, vector<int> &path,
} }
``` ```
## [39. 组合总和](https://leetcode.cn/problems/combination-sum/)
## [216. 组合总和 III](https://leetcode.cn/problems/combination-sum-iii/) ## [216. 组合总和 III](https://leetcode.cn/problems/combination-sum-iii/)

View File

@ -1,27 +1,31 @@
#include "s0039_combination_sum.hpp" #include "s0039_combination_sum.hpp"
void S0039::dfs(vector<int>& candidates, int target, vector<vector<int>>& ans, void combinationSumDFS(vector<int> &candidates, int target, int startIndex,
vector<int>& combine, int idx) { vector<int> &path, int sum,
if (idx == candidates.size()) { vector<vector<int>> &result) {
// 结束条件:总和等于 target 。不存在总和大于 target 的情况,因为已经被剪枝了
if (sum == target) {
result.push_back(path);
return; return;
} }
if (target == 0) {
ans.emplace_back(combine); // 开始迭代
return; int size = candidates.size();
} for (int i = startIndex; i < size; ++i) {
// 直接跳过 // 剪枝,当现在节点的 sum 已经超过了 target就没必要继续迭代了
dfs(candidates, target, ans, combine, idx + 1); if (sum + candidates[i] > target) break;
// 选择当前数 path.push_back(candidates[i]);
if (target - candidates[idx] >= 0) { combinationSumDFS(candidates, target, i, path, sum + candidates[i], result);
combine.emplace_back(candidates[idx]); path.pop_back();
dfs(candidates, target - candidates[idx], ans, combine, idx);
combine.pop_back();
} }
} }
vector<vector<int>> S0039::combinationSum(vector<int>& candidates, int target) { vector<vector<int>> S0039::combinationSum(vector<int> &candidates, int target) {
vector<vector<int>> ans; // 对 candidates 进行升序排序,这是为了进行剪枝
vector<int> combine; sort(candidates.begin(), candidates.end());
dfs(candidates, target, ans, combine, 0); // 初始化
return ans; vector<int> path{};
vector<vector<int>> result{};
combinationSumDFS(candidates, target, 0, path, 0, result);
return result;
} }