|
| 1 | +// Input: candidates = [2,3,5], target = 8 |
| 2 | +// Output: [[2,2,2,2],[2,3,3],[3,5]] |
| 3 | + |
| 4 | +// DFS/backtracking should be used - Find possilbe combinations till the end and backtrack to previous step to find other combinations |
| 5 | +// For example, if we have candidates [2,3,5] and target 8 |
| 6 | +// Start with empty combination [], target 8 |
| 7 | +// Add 2 -> [2], remaining 6 |
| 8 | +// Add 2 -> [2,2], remaining 4 |
| 9 | +// Add 2 -> [2,2,2], remaining 2 |
| 10 | +// Add 2 -> [2,2,2,2], remaining 0 (found a valid combination) |
| 11 | +// Backtrack to [2,2,2,3], remaining -1 (remaining is negative, backtrack) |
| 12 | +// Backtrack to [2,2,2,5], remaining -3 (remaining is negative, backtrack) |
| 13 | +// Backtrack to [2,2,3], remaining 1 (dead end, backtrack) |
| 14 | +// Backtrack to [2,2,5], remaining -3 (remaining is negative, backtrack) |
| 15 | +// Backtrack to [2,3], remaining 3 |
| 16 | +// Add 3 -> [2,3,3], remaining 0 (found a valid combination) |
| 17 | +// so on .. |
| 18 | + |
| 19 | +// When you dfs, always start from current index and allow reusing the same element or next index only to avoid duplicates / to get unique combination |
| 20 | +// Hence, if we starts from 2, next dfs calls can start from index of 2 or index of 3, but not index of 5 directly |
| 21 | +// Moreover, if we start from 3, next dfs calls can start from index of 3 or index of 5, but not index of 2 directly |
| 22 | + |
| 23 | + |
| 24 | +function combinationSum(candidates: number[], target: number): number[][] { |
| 25 | + const result: number[][] = [] |
| 26 | + |
| 27 | + function backtrack(remaining: number, combination: number[], startindex: number) { |
| 28 | + // Remaining is target - sum of combination |
| 29 | + // Base Case1: If remaining is 0, we found a valid combination -> add that combinations to result |
| 30 | + if (remaining === 0) { |
| 31 | + result.push([...combination]); |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + // Base Case2: If remaining is negative, no valid combination -> backtrack |
| 36 | + if (remaining < 0) { |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + // Explore further by trying each candidate starting from startindex |
| 41 | + // candidates = [2,3,5], target = 8 |
| 42 | + for (let i = startindex; i < candidates.length; i++) { |
| 43 | + // Choose the current number |
| 44 | + const currentNumber = candidates[i]; |
| 45 | + // Add the current number to the combination |
| 46 | + combination.push(currentNumber); |
| 47 | + |
| 48 | + // Explore further with updated remaining and current combination |
| 49 | + backtrack(remaining - currentNumber, combination, i); |
| 50 | + // Backtrack: remove the last added candidate to try next candidate |
| 51 | + combination.pop(); |
| 52 | + } |
| 53 | + } |
| 54 | + backtrack(target, [], 0); |
| 55 | + return result; |
| 56 | +}; |
0 commit comments