|
| 1 | +class Solution: |
| 2 | + def traverse(self, candidates: List[int], target: int, result: List[List[int]], current: List[int], starting: int): |
| 3 | + # 쑰건μ λ§μ‘±νλ κ²½μ° κ²°κ³Όμ μΆκ°νκ³ λ°νν¨μΌλ‘μ¨ μ½ μ€νμ λ μ΄μ μμ§ μμ |
| 4 | + if target == 0: |
| 5 | + result.append(current[:]) |
| 6 | + return |
| 7 | + |
| 8 | + # μμ 쑰건μ λ§μ‘±νμ§ μλ κ²½μ° λ°νν¨μΌλ‘μ¨ μ½ μ€νμ λ μ΄μ μμ§ μμ |
| 9 | + if target < 0: |
| 10 | + return |
| 11 | + |
| 12 | + # starting μΈλ±μ€κ° νμν μ΄μ λ, κ²°κ³Ό μΌμ΄μ€μ μμ μμκ° μ€μνμ§ μκΈ° λλ¬Έ |
| 13 | + # μ¦, [2, 3]κ³Ό [3, 2]κ° κ°μ μΌμ΄μ€μ΄κΈ° λλ¬Έ |
| 14 | + # μΈλ±μ€μ λ°λ₯Έ κ°μ§μΉκΈ° μ μ©, μ μ¬μ μ€λ³΅ μΌμ΄μ€ μ κ±° |
| 15 | + for i in range(starting, len(candidates)): |
| 16 | + candidate = candidates[i] |
| 17 | + |
| 18 | + # μμ ν¬μ
νλ current λ°°μ΄μ μΈ-λ©λͺ¨λ¦¬ μ‘°μνμ¬ μμ μ½μ
|
| 19 | + current.append(candidate) |
| 20 | + |
| 21 | + # μ½ μ€νμ μν΄, μ¬κΈ°μ νΈμΆν traverseκ° λ¨Όμ resultμ κ²°κ³Όλ₯Ό μΆκ° |
| 22 | + # λ§μ½ μ΄ "μμ νΈμΆ"μ΄ μ‘°κ±΄μ λ§μ‘±νλ€λ©΄, μμμ μ²λ¦¬νκ³ λ°ν |
| 23 | + self.traverse(candidates, target - candidate, result, current, i) |
| 24 | + |
| 25 | + # μΈ-λ©λͺ¨λ¦¬ μ‘°μν current λ°°μ΄μ μμ볡ꡬ |
| 26 | + current.pop() |
| 27 | + |
| 28 | + # λͺ¨λ μμ νΈμΆμ λ§λ¬΄λ¦¬μ§μ traverse ν¨μλ Noneμ λ°ν |
| 29 | + |
| 30 | + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: |
| 31 | + candidates.sort() |
| 32 | + |
| 33 | + result = [] |
| 34 | + current = [] # DFS μν μ€, νμ¬κΉμ§μ κ²°κ³Όλ₯Ό λ΄μ λ°°μ΄ |
| 35 | + |
| 36 | + self.traverse(candidates, target, result, current, 0) |
| 37 | + |
| 38 | + return result |
0 commit comments