Skip to content

Commit 762cfe1

Browse files
committed
combination sum solutions
1 parent 9c8fe48 commit 762cfe1

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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

Comments
ย (0)