|
| 1 | +[](https://github.com/LeetCode-in-TypeScript/LeetCode-in-TypeScript) |
| 2 | +[](https://github.com/LeetCode-in-TypeScript/LeetCode-in-TypeScript/fork) |
| 3 | + |
| 4 | +## 39\. Combination Sum |
| 5 | + |
| 6 | +Medium |
| 7 | + |
| 8 | +Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**. |
| 9 | + |
| 10 | +The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different. |
| 11 | + |
| 12 | +It is **guaranteed** that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input. |
| 13 | + |
| 14 | +**Example 1:** |
| 15 | + |
| 16 | +**Input:** candidates = [2,3,6,7], target = 7 |
| 17 | + |
| 18 | +**Output:** [[2,2,3],[7]] |
| 19 | + |
| 20 | +**Explanation:** |
| 21 | + |
| 22 | + 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. |
| 23 | + 7 is a candidate, and 7 = 7. |
| 24 | + These are the only two combinations. |
| 25 | + |
| 26 | +**Example 2:** |
| 27 | + |
| 28 | +**Input:** candidates = [2,3,5], target = 8 |
| 29 | + |
| 30 | +**Output:** [[2,2,2,2],[2,3,3],[3,5]] |
| 31 | + |
| 32 | +**Example 3:** |
| 33 | + |
| 34 | +**Input:** candidates = [2], target = 1 |
| 35 | + |
| 36 | +**Output:** [] |
| 37 | + |
| 38 | +**Example 4:** |
| 39 | + |
| 40 | +**Input:** candidates = [1], target = 1 |
| 41 | + |
| 42 | +**Output:** [[1]] |
| 43 | + |
| 44 | +**Example 5:** |
| 45 | + |
| 46 | +**Input:** candidates = [1], target = 2 |
| 47 | + |
| 48 | +**Output:** [[1,1]] |
| 49 | + |
| 50 | +**Constraints:** |
| 51 | + |
| 52 | +* `1 <= candidates.length <= 30` |
| 53 | +* `1 <= candidates[i] <= 200` |
| 54 | +* All elements of `candidates` are **distinct**. |
| 55 | +* `1 <= target <= 500` |
| 56 | + |
| 57 | +## Solution |
| 58 | + |
| 59 | +```typescript |
| 60 | +function combinationSum(candidates: number[], target: number): number[][] { |
| 61 | + const result: number[][] = [] |
| 62 | + const path: number[] = [] |
| 63 | + |
| 64 | + const comFunct = (index: number, sum: number) => { |
| 65 | + if (sum === target) { |
| 66 | + result.push([...path]) |
| 67 | + return |
| 68 | + } |
| 69 | + if (sum > target) return |
| 70 | + for (let i = index; i < candidates.length; i++) { |
| 71 | + path.push(candidates[i]) |
| 72 | + comFunct(i, sum + candidates[i]) |
| 73 | + path.pop() |
| 74 | + } |
| 75 | + } |
| 76 | + comFunct(0, 0) |
| 77 | + return result |
| 78 | +} |
| 79 | + |
| 80 | +export { combinationSum } |
| 81 | +``` |
0 commit comments