Combination sum problem using JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we are given a set of candidate numbers (without duplicates) and a target number (target).

We are required to write a function that finds all unique combinations in candidates where the candidate numbers sum to the target.

The same repeated number may be chosen from candidates an unlimited number of times.

Note

• All numbers (including target) will be positive integers.

• The solution set must not contain duplicate combinations.

For example

If the inputs are −

candidates = [2,3,6,7], target = 7,

The solution to this can be −

[
[7],
[2,2,3]
];

Since the problem is to get all the possible results, not the best or the number of results, thus we don’t need to consider Dynamic Programming, backtracking approach using recursion is needed to handle it.

Example

Following is the code −

const recursiveSum = (
candidates,
remainingSum,
finalCombinations = [],
currentCombination = [],
startFrom = 0,
) => {
if (remainingSum < 0) {
return finalCombinations;
}
if (remainingSum === 0) {
finalCombinations.push(currentCombination.slice());
return finalCombinations;
}
for (let candidateIndex = startFrom; candidateIndex < candidates.length; candidateIndex += 1) {
const currentCandidate = candidates[candidateIndex];
currentCombination.push(currentCandidate);
recursiveSum(
candidates,
remainingSum - currentCandidate,
finalCombinations,
currentCombination,
candidateIndex,
);
currentCombination.pop();
}
return finalCombinations;
}
const combinationSum = (candidates, target) => recursiveSum(candidates, target);
console.log(combinationSum([2, 3, 6, 7], 7));

Output

Following is the output on console −

[ [ 2, 2, 3 ], [ 7 ] ]
Published on 11-Dec-2020 13:21:25