Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added solution for "combination sum" problem(Leetcode 39) #7

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions combination_sum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@

// Problem Link: https://leetcode.com/problems/combination-sum/

class Solution
{
public:
bool helper(vector<int> &nums, int currSum, int target, unordered_map<int, int> &perm, vector<unordered_map<int, int>> &collection, int index)
{
if (currSum > target)
{
return false;
}

if (currSum == target)
{
bool found = false;
for (auto m : collection)
{
if (m == perm)
{
found = true;
break;
}
}
if (!found)
{
collection.push_back(perm);
}
return true;
}

for (int i = index; i < nums.size(); i++)
{
perm[nums[i]] += 1;
currSum += nums[i];
bool flag = helper(nums, currSum, target, perm, collection, i);
perm[nums[i]] -= 1;
if (perm[nums[i]] <= 0)
{
perm.erase(nums[i]);
}
currSum -= nums[i];
if (!flag)
{
break;
}
}

return true;
}

vector<vector<int>> combinationSum(vector<int> &candidates, int target)
{
unordered_map<int, int> perm;
vector<unordered_map<int, int>> collection;

sort(candidates.begin(), candidates.end());
helper(candidates, 0, target, perm, collection, 0);

vector<vector<int>> allPerms;

for (auto m : collection)
{
vector<int> p;
for (auto it : m)
{
int num = it.first;
int freq = it.second;
while (freq--)
{
p.push_back(num);
}
}
allPerms.push_back(p);
}

return allPerms;
}
};