Leetcode 40 Solution
This article provides solution to leetcode question 40 (combination-sum-ii).
Access this page by simply typing in "lcs 40" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/combination-sum-ii
Solution
class Solution {
vector<int> cur;
set<vector<int>> m_res;
public:
void combinationSum(vector<int>& candidates, int target, int cur_sum, int from) {
if (cur_sum > target)
return;
else if (cur_sum == target)
{
m_res.insert(cur);
return;
}
for (int i = from; i < candidates.size(); i++)
{
int v = candidates[i];
cur.push_back(v);
int next = i + 1;
combinationSum(candidates, target, cur_sum + v, i + 1);
cur.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
combinationSum(candidates, target, 0, 0);
vector<vector<int>> res;
for (auto it = m_res.begin(); it != m_res.end(); it++)
res.push_back(*it);
return res;
}
};