151 DSA Problem journey

151 DSA Problem journey

Combination Sum

Q20: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.

The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

Example :

Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
class Solution {
 void search(vector<int>& num, int next, vector<int>& pSol, int target, vector<vector<int> >& result)
        if(target == 0)
        if(next == num.size() || target - num[next] < 0)

        search(num, next, pSol, target - num[next], result);

        search(num, next + 1, pSol, target, result);
    vector<vector<int>> combinationSum(vector<int> &num, int target) {
         vector<vector<int> > result;
        sort(num.begin(), num.end());
        vector<int> pSol;
        search(num, 0, pSol, target, result);
        return result;       
>In this solution we use the concept of backtracking ,we which we call the function
again and again until we get the desire output
>In this code we call the function search again and again for the solution when 
we find the solution we push that answer in the result vector and than return the 
result answer.
#If anyone have better solution so please comment:)

Did you find this article valuable?

Support GAURAV YADAV by becoming a sponsor. Any amount is appreciated!