|
| 1 | +/** |
| 2 | + * @param {number[]} candidates - candidate numbers we're picking from. |
| 3 | + * @param {number} remainingSum - remaining sum after adding candidates to currentCombination. |
| 4 | + * @param {number[][]} finalCombinations - resulting list of combinations. |
| 5 | + * @param {number[]} currentCombination - currently explored candidates. |
| 6 | + * @param {number} startFrom - index of the candidate to start further exploration from. |
| 7 | + * @return {number[][]} |
| 8 | + */ |
| 9 | +function combinationSumRecursive( |
| 10 | + candidates, |
| 11 | + remainingSum, |
| 12 | + finalCombinations = [], |
| 13 | + currentCombination = [], |
| 14 | + startFrom = 0, |
| 15 | +) { |
| 16 | + if (remainingSum < 0) { |
| 17 | + // By adding another candidate we've gone below zero. |
| 18 | + // This would mean that last candidate was not acceptable. |
| 19 | + return finalCombinations; |
| 20 | + } |
| 21 | + |
| 22 | + if (remainingSum === 0) { |
| 23 | + // In case if after adding the previous candidate out remaining sum |
| 24 | + // became zero we need to same current combination since it is one |
| 25 | + // of the answer we're looking for. |
| 26 | + finalCombinations.push(currentCombination.slice()); |
| 27 | + |
| 28 | + return finalCombinations; |
| 29 | + } |
| 30 | + |
| 31 | + // In case if we haven't reached zero yet let's continue to add all |
| 32 | + // possible candidates that are left. |
| 33 | + for (let candidateIndex = startFrom; candidateIndex < candidates.length; candidateIndex += 1) { |
| 34 | + const currentCandidate = candidates[candidateIndex]; |
| 35 | + |
| 36 | + // Let's try to add another candidate. |
| 37 | + currentCombination.push(currentCandidate); |
| 38 | + |
| 39 | + // Explore further option with current candidate being added. |
| 40 | + combinationSumRecursive( |
| 41 | + candidates, |
| 42 | + remainingSum - currentCandidate, |
| 43 | + finalCombinations, |
| 44 | + currentCombination, |
| 45 | + candidateIndex, |
| 46 | + ); |
| 47 | + |
| 48 | + // BACKTRACKING. |
| 49 | + // Let's get back, exclude current candidate and try another ones later. |
| 50 | + currentCombination.pop(); |
| 51 | + } |
| 52 | + |
| 53 | + return finalCombinations; |
| 54 | +} |
| 55 | + |
| 56 | +/** |
| 57 | + * Backtracking algorithm of finding all possible combination for specific sum. |
| 58 | + * |
| 59 | + * @param {number[]} candidates |
| 60 | + * @param {number} target |
| 61 | + * @return {number[][]} |
| 62 | + */ |
| 63 | +export default function combinationSum(candidates, target) { |
| 64 | + return combinationSumRecursive(candidates, target); |
| 65 | +} |
0 commit comments