leetcode/src/s0039_combination_sum.cpp

28 lines
743 B
C++
Raw Normal View History

2022-11-22 13:31:25 +00:00
#include "s0039_combination_sum.hpp"
2022-11-30 10:20:36 +00:00
void S0039::dfs(vector<int>& candidates, int target, vector<vector<int>>& ans,
vector<int>& combine, int idx) {
2022-11-22 13:31:25 +00:00
if (idx == candidates.size()) {
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();
}
}
2022-11-30 10:20:36 +00:00
vector<vector<int>> S0039::combinationSum(vector<int>& candidates, int target) {
2022-11-22 13:31:25 +00:00
vector<vector<int>> ans;
vector<int> combine;
dfs(candidates, target, ans, combine, 0);
return ans;
}