Leetcode Combination Sum problem solution

In the Leetcode Combination Sum problem solution 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 1:

Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
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.


Example 2:

Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]

Constraints:

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • All elements of candidates are distinct.
  • 1 <= target <= 40

Solution in C Programming

void goUp(int* len, int* sum, int* candidates, int size, int* index)
{
    do {
        *sum -= candidates[index[*len]];
        (*len)--;
    } while (*len >= 0 && index[*len] + 1 == size); 
    if (*len >= 0) {
        *sum -= candidates[index[*len]];
        index[*len]++;
        *sum += candidates[index[*len]];
    }
}

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** combinationSum(int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes)
{
    int** output = (int**)malloc(150 * sizeof(int*));
    *returnColumnSizes = (int*)malloc(150 * sizeof(int));
    // Sort the candidates array
    for (int i = 0; i < candidatesSize; i++) {
        for (int j = i + 1; j < candidatesSize; j++) {
            if (candidates[j] < candidates[i]) {
                int temp = candidates[i];
                candidates[i] = candidates[j];
                candidates[j] = temp;
            }
        }
    }
    *returnSize = 0;
    int* index = (int*)malloc(target * sizeof(int));
    int sum = candidates[0], len = 0;
    index[0] = 0;
    do {
        if (sum == target) {
            output[*returnSize] = (int*)malloc((len + 1) * sizeof(int));
            for (int i = 0; i <= len; i++) {
                output[*returnSize][i] = candidates[index[i]];
            }
            (*returnColumnSizes)[*returnSize] = len + 1;
            (*returnSize)++;
            goUp(&len, &sum, candidates, candidatesSize, index);
        } else if (sum > target) {
            goUp(&len, &sum, candidates, candidatesSize, index);
        } else {
            len++;
            index[len] = index[len - 1];
            sum += candidates[index[len]];
        }
    } while (len >= 0);
    return output;
}

Solution in C++ Programming

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> v;
        //sort(candidates.begin(),candidates.end());
        vector<int> a;
        backtrack(v,candidates,target,0,0,a);
        return v;
    }
    
    
    void backtrack (vector<vector<int>>&v, vector<int>& candidates, int target, int start, int sum, vector<int> &a){
        
        if(start>candidates.size()-1){
            return ;
        }
        
        if(sum>target){
            return;
        }
        
        else if(sum==target){
                vector<int> b =a;
                v.push_back(b);
        }
        
        for(int i =start; i<candidates.size(); i++){
            
           
                a.push_back(candidates[i]);
                backtrack(v,candidates,target,i,sum+candidates[i],a);
                a.pop_back();
            
        }
        
      return;  
        
    }
};

Solution in Java Programming

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList();
        backtracking(candidates, target, result, new ArrayList<Integer>(), 0, 0);
        return result;
    }
    private void backtracking(int[] candidates, int target, List<List<Integer>> result, ArrayList<Integer> list, int start, int sum){
        if (sum == target){
            result.add(new ArrayList<Integer>(list));
            return;
        }
        if (sum > target)
            return;
        for (int i  = start; i < candidates.length; i++){
            list.add(candidates[i]);
            backtracking(candidates, target, result, list, i, sum + candidates[i]);
            list.remove(list.size()-1);
        }
    }
}

Solution in Python Programming

class Solution:
    def combinationSum(self, candidates, target):
        
        N = len(candidates)
        combination = []
        result = []
        
        def helper(i, sum):
            
            if sum > target or i >= N:
                return
            
            if sum == target:
                result.append(combination[:])
                return
            
            for k in range(i, N):
                combination.append(candidates[k])
                helper(k, sum+candidates[k])
                combination.pop()
        
        helper(0, 0)
        
        return result

Solution in C# Programming

public class Solution {
    private HashSet<int> _combinationsSet;
    
    public IList<IList<int>> CombinationSum(int[] candidates, int target) {
        IList<IList<int>> combinationsList = new List<IList<int>>();
        _combinationsSet = new HashSet<int>();
        findCombinations(candidates, target, (v) => combinationsList.Add(v), new List<int>(), true);
        return combinationsList;
    }
    
    private void findCombinations(int[] candidates, int target, Action<IList<int>> addCombination, IList<int> combination, bool topOfStack) {
        if (combination.AsQueryable().Sum() == target) {
          AddToCombinationsList(addCombination, combination);
        }
        
        if (!(target - combination.AsQueryable().Sum() < 0)) {
            for (int i = 0; i < candidates.Length; ++i) {
                if (candidates[i] <= target)
                {
                    combination.Add(candidates[i]);
                    findCombinations(candidates, target, addCombination, combination, false);
                    combination.RemoveAt(combination.Count()-1);
                } else {
                    break;
                }
            }
        }
    }
    
    private void AddToCombinationsList(Action<IList<int>> addCombination, IList<int> combination){
         int combNum = 0;
         int counter = 0;
         
         var copy = new List<int>();
         foreach (var elem in combination) {
             copy.Add(elem);
         }
         copy.Sort();
         
         foreach (var elem in copy) {
             combNum += elem * ((int) Math.Pow(10, counter));
             counter++;
         }
         
         if (!_combinationsSet.Contains(combNum)) {
             _combinationsSet.Add(combNum);
             addCombination(copy);
             return;
         }
    }
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *