From 8f3ebbdd3d5d301602bdc55890b6d693245e2cea Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Tue, 22 Nov 2022 21:31:25 +0800 Subject: [PATCH] s0039 --- include/s0039_combination_sum.hpp | 15 +++++++++++++++ src/s0039_combination_sum.cpp | 30 ++++++++++++++++++++++++++++++ tests/s0039_combination_sum.cpp | 27 +++++++++++++++++++++++++++ 3 files changed, 72 insertions(+) create mode 100644 include/s0039_combination_sum.hpp create mode 100644 src/s0039_combination_sum.cpp create mode 100644 tests/s0039_combination_sum.cpp diff --git a/include/s0039_combination_sum.hpp b/include/s0039_combination_sum.hpp new file mode 100644 index 0000000..66dc6e2 --- /dev/null +++ b/include/s0039_combination_sum.hpp @@ -0,0 +1,15 @@ +#ifndef S0039_COMBINATION_SUM_HPP +#define S0039_COMBINATION_SUM_HPP + +#include +#include +#include + +using namespace std; + +class Solution { + public: + vector> combinationSum(vector& candidates, int target); +}; + +#endif diff --git a/src/s0039_combination_sum.cpp b/src/s0039_combination_sum.cpp new file mode 100644 index 0000000..52907b5 --- /dev/null +++ b/src/s0039_combination_sum.cpp @@ -0,0 +1,30 @@ +#include "s0039_combination_sum.hpp" + +#include + +void dfs(vector& candidates, int target, vector>& ans, + vector& 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> Solution::combinationSum(vector& candidates, + int target) { + vector> ans; + vector combine; + dfs(candidates, target, ans, combine, 0); + return ans; +} diff --git a/tests/s0039_combination_sum.cpp b/tests/s0039_combination_sum.cpp new file mode 100644 index 0000000..082519b --- /dev/null +++ b/tests/s0039_combination_sum.cpp @@ -0,0 +1,27 @@ +#include "s0039_combination_sum.hpp" + +#include + +TEST(Problem39, Case1) { + vector candidates{2, 3, 6, 7}; + int target{7}; + vector> o{{7}, {2, 2, 3}}; + Solution solution; + EXPECT_EQ(solution.combinationSum(candidates, target), o); +} + +TEST(Problem39, Case2) { + vector candidates{2, 3, 5}; + int target{8}; + vector> o{{3, 5}, {2, 3, 3}, {2, 2, 2, 2}}; + Solution solution; + EXPECT_EQ(solution.combinationSum(candidates, target), o); +} + +TEST(Problem39, Case3) { + vector candidates{2}; + int target{1}; + vector> o{}; + Solution solution; + EXPECT_EQ(solution.combinationSum(candidates, target), o); +}