|
| 1 | +/** |
| 2 | + * Finds all unique combinations of numbers from the candidates array that sum up to the target. |
| 3 | + * |
| 4 | + * @param candidates - An array of numbers. |
| 5 | + * @param target - The target sum. |
| 6 | + * @returns An array of arrays, each containing a unique combination of numbers that sum up to the target. |
| 7 | + * |
| 8 | + * Time Complexity: O(n^2) |
| 9 | + * Space Complexity: O(n) |
| 10 | + */ |
| 11 | +function combinationSum(candidates: number[], target: number): number[][] { |
| 12 | + // 1. Initialize result array |
| 13 | + let combinations: number[][] = []; |
| 14 | + let candidate: number[] = []; |
| 15 | + |
| 16 | + // 2. Define recursive function |
| 17 | + function combination(start: number, total: number) { |
| 18 | + console.log(`start:${start}, total:${total}`) |
| 19 | + if (target < total) { |
| 20 | + // 3. If total is greater than target, return |
| 21 | + return; |
| 22 | + } else if (target === total) { |
| 23 | + // 4. If total is equal to target, push candidate to result |
| 24 | + combinations.push([...candidate]) |
| 25 | + return; |
| 26 | + } else { |
| 27 | + // 5. If total is less than target, iterate through candidates |
| 28 | + for (let i = start; i < candidates.length; i++) { |
| 29 | + // 6. Push candidate to result |
| 30 | + candidate.push(candidates[i]) |
| 31 | + // 7. Recursively call combination function |
| 32 | + combination(i, total + candidates[i]) |
| 33 | + // 8. Pop candidate from result |
| 34 | + candidate.pop(); |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + combination(0, 0); |
| 39 | + |
| 40 | + return combinations; |
| 41 | +}; |
0 commit comments