Open In App

Combination Sum Problem in JavaScript

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In the Combination problem we are given an array of integers and a target number, we have to return all unique possible combinations whose element sum is equal to the target value.

There are several approaches available in JavaScript to solve the combination sum problem which are as follows:

Brute force Approach ( Using Recursion)

We will create a recursive function “findCombination” helper function which will recursively find all combinations that sum up to the target. The base case for function is when the Current Sum equals the target, pushing the Current Combination to the answer array. Recursively call the function and consider two possibilities either we have to pick the element and add it to current Sum or we will skip the current element.

Example: To demonstrate Combination sum problem using recursive approach.

JavaScript
function combinationSum(nums, target) {

    // Helper function 
    function findCombinations(start, currentSum
        , currentCombination) {
        
        // Base case
        if (currentSum === target) {
            result.push([...currentCombination]);
            return;
        }
        
        //  one more edge case
        if (currentSum > target || start === nums.length) {
            return;
        }
        
        // include current element 
        findCombinations(start, currentSum + nums[start],
            currentCombination.concat(nums[start]));
            
        // exclude current element
        findCombinations(start + 1, currentSum, currentCombination);
    }


    const result = [];

    findCombinations(0, 0, []);
    
    // Return 
    return result;
}

const nums = [2, 3, 6, 7];
const target = 7;
console.log("possible combinations are : ",
    combinationSum(nums, target));

Output
possible combinations are :  [ [ 2, 2, 3 ], [ 7 ] ]

Time Complexity: O(2n)

Space Complexity: O(n*m)

Optimal Approach (Using Dynamic Approach)

We use recursion + memoization i.e. top-down dynamic programming approach. Initialize an empty object to store computed results. Define a nested function, dp, for recursive combination finding with memoization. Handle base cases and iterate over nums, recursively calling dp with updated target, then concatenate num with each combination obtained and push to res. Memoize res with the current target as the key. Return the result obtained from dp for the given target.

Example: To demonstrate Combination sum problem using recursion with memoization

JavaScript
function combinationSum(nums, target) {
    const memo = {};

    // remove duplicates from the array
    nums = nums.sort((a, b) => a - b).filter((num, index, arr)
         => index === 0 || num !== arr[index - 1]);

    function dp(start, target) {
        if (memo[target]) {
            return memo[target];
        }
        if (target === 0) {
            return [[]];
        }
        if (target < 0) {
            return [];
        }
        const res = [];
        for (let i = start; i < nums.length; i++) {
            const num = nums[i];
            if (target - num >= 0) {
                for (const comb of dp(i, target - num)) {
                    res.push([num, ...comb]);
                }
            }
        }
        memo[target] = res;
        return res;
    }

    return dp(0, target);
}


const nums = [2, 3, 6, 7];
const target = 7;
console.log("possible combinations are " ,
            combinationSum(nums, target));

Output
possible combinations are  [ [ 2, 2, 3 ], [ 7 ] ]

Time Complexity: O(n2 * m)

Space Complexity: O(m * k)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads