s0039
This commit is contained in:
parent
8ce5ca9166
commit
8f3ebbdd3d
15
include/s0039_combination_sum.hpp
Normal file
15
include/s0039_combination_sum.hpp
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
#ifndef S0039_COMBINATION_SUM_HPP
|
||||||
|
#define S0039_COMBINATION_SUM_HPP
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
#include <algorithm>
|
||||||
|
#include <iterator>
|
||||||
|
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
vector<vector<int>> combinationSum(vector<int>& candidates, int target);
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif
|
30
src/s0039_combination_sum.cpp
Normal file
30
src/s0039_combination_sum.cpp
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
#include "s0039_combination_sum.hpp"
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
void dfs(vector<int>& candidates, int target, vector<vector<int>>& ans,
|
||||||
|
vector<int>& combine, int idx) {
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
vector<vector<int>> Solution::combinationSum(vector<int>& candidates,
|
||||||
|
int target) {
|
||||||
|
vector<vector<int>> ans;
|
||||||
|
vector<int> combine;
|
||||||
|
dfs(candidates, target, ans, combine, 0);
|
||||||
|
return ans;
|
||||||
|
}
|
27
tests/s0039_combination_sum.cpp
Normal file
27
tests/s0039_combination_sum.cpp
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
#include "s0039_combination_sum.hpp"
|
||||||
|
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
|
TEST(Problem39, Case1) {
|
||||||
|
vector<int> candidates{2, 3, 6, 7};
|
||||||
|
int target{7};
|
||||||
|
vector<vector<int>> o{{7}, {2, 2, 3}};
|
||||||
|
Solution solution;
|
||||||
|
EXPECT_EQ(solution.combinationSum(candidates, target), o);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Problem39, Case2) {
|
||||||
|
vector<int> candidates{2, 3, 5};
|
||||||
|
int target{8};
|
||||||
|
vector<vector<int>> o{{3, 5}, {2, 3, 3}, {2, 2, 2, 2}};
|
||||||
|
Solution solution;
|
||||||
|
EXPECT_EQ(solution.combinationSum(candidates, target), o);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Problem39, Case3) {
|
||||||
|
vector<int> candidates{2};
|
||||||
|
int target{1};
|
||||||
|
vector<vector<int>> o{};
|
||||||
|
Solution solution;
|
||||||
|
EXPECT_EQ(solution.combinationSum(candidates, target), o);
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user