diff --git a/src/index.js b/src/index.js index 2f25fb2..859f234 100644 --- a/src/index.js +++ b/src/index.js @@ -8,8 +8,35 @@ */ const combinationSumRecursive = ( - - } + candidates, + remainingSum, + finalCombinations = [], + currentCombination = [], + startFrom = 0 + ) => { + if (remainingSum === 0) { + finalCombinations.push(currentCombination.slice()); + currentCombination = []; + return finalCombinations; + } + else { + if (remainingSum < 0) + return []; + else { + for (let currentIndex = startFrom; currentIndex < candidates.length; currentIndex++) { + const currentNumber = candidates[currentIndex]; + combinationSumRecursive( + candidates, + remainingSum - currentNumber, + finalCombinations, + [...currentCombination, currentNumber], + currentIndex + ); + } + return finalCombinations; + } + } + } /** * Backtracking algorithm of finding all possible combination for specific sum.