From 753fb57f1bf0d1e5521b3ce2f35dacdc40bf47e5 Mon Sep 17 00:00:00 2001 From: Tanmay Tete <tanmay.tete@somaiya.edu> Date: Sun, 17 Oct 2021 22:05:01 +0530 Subject: [PATCH] Add combination_sum.cpp (medium leve problem) --- C++/combination_sum.cpp | 44 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 C++/combination_sum.cpp diff --git a/C++/combination_sum.cpp b/C++/combination_sum.cpp new file mode 100644 index 0000000..9590db9 --- /dev/null +++ b/C++/combination_sum.cpp @@ -0,0 +1,44 @@ +//PROBLEM-LINK=https://leetcode.com/problems/combination-sum/ +// Runtime: 4ms +// Memory Usage: 10 MB +class Solution +{ +public: + void cSum(vector<int> &candidates, int target, vector<int> ¤t, int sum, int index, vector<vector<int>> &result) + { + + if (sum == target) + { + vector<int> temp(current.begin(), current.end()); + sort(temp.begin(), temp.end()); + if (count(result.begin(), result.end(), temp) == 0) + result.push_back(temp); + return; + } + + if (sum > target) + { + return; + } + + for (int i = index; i < candidates.size(); i++) + { + current.push_back(candidates[i]); + cSum(candidates, target, current, sum + candidates[i], i, result); + current.pop_back(); + } + + return; + } + + vector<vector<int>> combinationSum(vector<int> &candidates, int target) + { + + vector<vector<int>> result; + vector<int> current; + + cSum(candidates, target, current, 0, 0, result); + + return result; + } +}; \ No newline at end of file