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
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;
@ -10,8 +9,6 @@ using namespace std;
class S0039 {
public:
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

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/)

View File

@ -1,27 +1,31 @@
#include "s0039_combination_sum.hpp"
void S0039::dfs(vector<int>& candidates, int target, vector<vector<int>>& ans,
vector<int>& combine, int idx) {
if (idx == candidates.size()) {
void combinationSumDFS(vector<int> &candidates, int target, int startIndex,
vector<int> &path, int sum,
vector<vector<int>> &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<vector<int>> S0039::combinationSum(vector<int> &candidates, int target) {
vector<vector<int>> ans;
vector<int> combine;
dfs(candidates, target, ans, combine, 0);
return ans;
// 对 candidates 进行升序排序,这是为了进行剪枝
sort(candidates.begin(), candidates.end());
// 初始化
vector<int> path{};
vector<vector<int>> result{};
combinationSumDFS(candidates, target, 0, path, 0, result);
return result;
}