Skip to content

Commit 1c238ad

Browse files
committed
solve(w03): 39. Combination Sum
1 parent 3f656d0 commit 1c238ad

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

โ€Žcombination-sum/seungriyou.py

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# https://leetcode.com/problems/combination-sum/
2+
3+
from typing import List
4+
5+
class Solution:
6+
def combinationSum1(self, candidates: List[int], target: int) -> List[List[int]]:
7+
"""
8+
[Complexity]
9+
- TC: O(n^{target/min(candidates)})
10+
- ์žฌ๊ท€ ํ˜ธ์ถœ ํŠธ๋ฆฌ์˜ ์ตœ๋Œ€ height๋Š” target/min(candidates) (์ค‘๋ณต ๊ฐ€๋Šฅํ•˜๋ฏ€๋กœ)
11+
- ๊ฐ step์—์„œ ์ตœ๋Œ€ nํšŒ ์žฌ๊ท€ ํ˜ธ์ถœ (for i in range(idx, n))
12+
- SC: O(target/min(candidates)) (* res ์ œ์™ธ)
13+
- recursion stack = ์ตœ๋Œ€ O(target/min(candidates))
14+
- combi = ์ตœ๋Œ€ O(target/min(candidates))
15+
16+
[Approach]
17+
backtracking(idx = ํ˜„์žฌ ๋ณด๊ณ ์žˆ๋Š” ์›์†Œ์˜ ์ธ๋ฑ์Šค, tot_sum = ํ˜„์žฌ๊นŒ์ง€์˜ ํ•ฉ)์œผ๋กœ ์ ‘๊ทผํ•œ๋‹ค.
18+
- base condition: tot_sum์ด target๊ณผ ๊ฐ™์œผ๋ฉด res์— ์ถ”๊ฐ€ํ•˜๊ณ , target ๋ณด๋‹ค ํฌ๋ฉด ์ข…๋ฃŒ
19+
- recursion: ํ˜„์žฌ ๋ณด๊ณ ์žˆ๋Š” ์›์†Œ์˜ ์ธ๋ฑ์Šค์˜ ์ดํ›„์— ์žˆ๋Š” ์›์†Œ๋“ค์„ backtracking์œผ๋กœ ๊ฒ€์‚ฌ
20+
(* "same number may be chosen from candidates" ์ด๋ฏ€๋กœ!)
21+
"""
22+
n = len(candidates)
23+
combi = []
24+
res = []
25+
26+
def backtracking(idx, tot_sum):
27+
# base condition
28+
if tot_sum == target:
29+
res.append(combi[:])
30+
return
31+
if tot_sum > target:
32+
return
33+
34+
# recur
35+
for i in range(idx, n):
36+
c = candidates[i]
37+
combi.append(c)
38+
backtracking(i, tot_sum + c)
39+
combi.pop()
40+
41+
backtracking(0, 0)
42+
43+
return res
44+
45+
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
46+
"""
47+
[Complexity]
48+
- TC: O(n^{target/min(candidates)})
49+
- SC: O(target/min(candidates)) (* res ์ œ์™ธ)
50+
51+
[Approach]
52+
๊ธฐ์กด backtracking ํ’€์ด์— ์ •๋ ฌ์„ ์ถ”๊ฐ€ํ•ด์„œ ์กฐ๊ธˆ ๋” ์ตœ์ ํ™”ํ•  ์ˆ˜ ์žˆ๋‹ค.
53+
์ฆ‰, candidates๋ฅผ ์ •๋ ฌํ•œ ํ›„, ๋งค ๋‹จ๊ณ„์—์„œ candidates[idx] > target - tot_sum ์ผ ๋•Œ๋„ ์ข…๋ฃŒํ•œ๋‹ค.
54+
์ด๋ก ์ ์œผ๋กœ ๋ณต์žก๋„๋Š” ๋™์ผํ•˜๋‚˜(TC์˜ ๊ฒฝ์šฐ, ์ •๋ ฌ์— ๋“œ๋Š” O(nlogn) ๋ณด๋‹ค ๋ฐฑํŠธ๋ž˜ํ‚น์— ๋“œ๋Š” O(n^m)์ด ๋” ์ง€๋ฐฐ์ ), early stop์ด ๊ฐ€๋Šฅํ•ด์ง„๋‹ค.
55+
"""
56+
n = len(candidates)
57+
combi = []
58+
res = []
59+
60+
candidates.sort() # -- ์ •๋ ฌ
61+
62+
def backtracking(idx, tot_sum):
63+
# base condition
64+
if tot_sum == target:
65+
res.append(combi[:])
66+
return
67+
if tot_sum > target or candidates[idx] > target - tot_sum: # -- optimize
68+
return
69+
70+
# recur
71+
for i in range(idx, n):
72+
c = candidates[i]
73+
combi.append(c)
74+
backtracking(i, tot_sum + c)
75+
combi.pop()
76+
77+
backtracking(0, 0)
78+
79+
return res

0 commit comments

Comments
ย (0)