|
| 1 | +class Solution: |
| 2 | + def combinationSum(self, candidates: list[int], target: int) -> list[list[int]]: |
| 3 | + """ |
| 4 | + μ£Όμ΄μ§ μ«μ λͺ©λ‘μμ λͺ©ννλ ν©μ λ§λ€ μ μλ μ‘°ν©μ μ°Ύλ ν¨μ |
| 5 | + μ«μλ λμΌ μ«μλ₯Ό μ¬λ¬λ² μ¬μ©ν΄λ λ¨ |
| 6 | +
|
| 7 | + λ°©λ²: |
| 8 | + DFS λ°©μμ μ¬μ©ν¨. |
| 9 | + - νμ¬ μΈλ±μ€λ₯Ό κΈ°μ€μΌλ‘, |
| 10 | + (μ νμ§) |
| 11 | + νμ¬ μμΉμ μ«μκ°μ νμ¬ μ‘°ν©μ ν¬ν¨ν μ§ |
| 12 | + - νμ¬ ν©μ λ§λ€κΈ° μν΄ λ¨μ κ° - νμ¬ κ°μ΄ 0 μ΄μμ΄λ©΄ ν¬ν¨ κ°λ₯ |
| 13 | + - νμ¬ κ°μ μ¬λ¬λ² μΈ μ μκΈ°μ μΈλ±μ€λ₯Ό λλ¦¬μ§ x |
| 14 | + νμ¬ μμΉμ μ«μκ°μ νμ¬ μ‘°ν©μ ν¬ν¨νμ§ μμμ§ |
| 15 | + - μ΄ μΈλ±μ€κ° λͺ©λ‘κΈΈμ΄λ₯Ό λμ΄κ°λ©΄ μλ¨ |
| 16 | + - ν©μ λλ¨Έμ§ κ°μ΄ 0μ΄λ©΄ λͺ©νμ λλ¬νκ² -> μ‘°ν© λͺ©λ‘μ ν¬ν¨ |
| 17 | +
|
| 18 | + Args: |
| 19 | + candidates (list[int]): μ¬μ©κ°λ₯ν μ«μ λͺ©λ‘. unique |
| 20 | + target (int): λͺ©ννλ ν© |
| 21 | + |
| 22 | + Returns: |
| 23 | + list[list[int]]: λͺ©ννλ ν©μ λ§λ€ μ μλ κ°λ₯ν μ«μ μ‘°ν©. unique |
| 24 | + """ |
| 25 | + combinations = list() |
| 26 | + def getCombination(idx, remain, path): |
| 27 | + """ |
| 28 | + νμ¬ ν¨μμμ μ¬κ·λ₯Ό μν helper ν¨μ |
| 29 | + """ |
| 30 | + if remain == 0: |
| 31 | + combinations.append(path) |
| 32 | + return |
| 33 | + if idx < len(candidates): |
| 34 | + curr = candidates[idx] |
| 35 | + if remain - curr >= 0: |
| 36 | + getCombination(idx, remain - curr, path + [curr]) |
| 37 | + getCombination(idx + 1, remain, path) |
| 38 | + return |
| 39 | + getCombination(0, target, []) |
| 40 | + return combinations |
0 commit comments