|
| 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