Combination Sum
Problem
Given an array of distinct integers candidates
and a target integer target
, return a list of all unique combinations of candidates
where the chosen numbers sum to target
. You may return the combinations in any order.
The same number may be chosen from candidates
an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
It is guaranteed that the number of unique combinations that sum up to target
is less than 150
combinations for the given input.
Solution Approach
Refer Code for Algorithm.
Expected Time complexity:
Click - to see solution code
- C++
class Solution {
int target;
vector<int> comb;
vector<int> arr;
vector<vector<int>> ans;
int sm, n;
public:
void find(int indx) {
if (sm == target) {
ans.push_back(arr);
return;
}
if (sm > target || indx >= n) return;
find(indx + 1);
for (int i = 1; i <= target / comb[indx]; i++) {
arr.push_back(comb[indx]);
sm += comb[indx];
find(indx + 1);
}
for (int i = 1; i <= target / comb[indx]; i++) {
arr.pop_back();
sm -= comb[indx];
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
this->comb = candidates;
this->target = target;
this->n = candidates.size();
this->sm = 0;
find(0);
return ans;
}
};