C++: Combination Sum

Thought Process

To solve the Combination Sum problem, we use backtracking. We start by iterating through the candidates array and recursively build combinations that sum up to the target. If the sum exceeds the target, we backtrack and try the next candidate.

class Solution {
public:
    void backTrack(vector<vector<int>> &ans, vector<int> tmp, vector<int>& candidates, int target,int start){

        if(target<0)
            return;
        if(target==0){
            ans.push_back(tmp);
        }
        for(int i=start;i<candidates.size();i++){
            // Add an Element to the List and Taking that element try to find the solution
            tmp.push_back(candidates[i]);
            backTrack(ans,tmp,candidates,target-candidates[i], i);
            // Finally, remove the added Element (backTrackStep)
            tmp.pop_back();
        }
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {

        vector<vector<int>> ans;
        vector<int> tmp;
        backTrack(ans,tmp,candidates,target, 0);
        return ans;
    }
};

Code Complexity

Time Complexity: O(2n)

The algorithm explores all possible combinations of the candidates, leading to an exponential time complexity, where 'n' is the size of the input.

Space Complexity: O(n)

The recursion stack depth is proportional to the size of the input('n'), and the temporary vector stores intermediate results.

Code copied!