Skip to content

Commit 1205cd0

Browse files
committed
feat: Add Combination Sum solutions
1 parent ba0ac0a commit 1205cd0

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution:
2+
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
3+
"""
4+
Intuition:
5+
๋ฆฌ์ŠคํŠธ์˜ ๊ฐ ์›์†Œ๋Š” ์ค‘๋ณตํ•ด์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.
6+
๊ทธ๋ ‡๋‹ค๋ฉด target์€ ์žฌ๊ท€์ ์œผ๋กœ ์›์†Œ๋ฅผ ์‚ฌ์šฉํ•ด์„œ
7+
๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ํƒ์ƒ‰ํ•œ๋‹ค.
8+
9+
Time Complexity:
10+
O(N^2 log N):
11+
์ดˆ๊ธฐ์— ๋ฆฌ์ŠคํŠธ์˜ ์›์†Œ๋ฅผ ์ •๋ ฌํ•˜๋Š” ๋ฐ์— O(N log N)์ด ์†Œ์š”๋œ๋‹ค.
12+
๋˜ํ•œ, ์žฌ๊ท€ ํ•จ์ˆ˜๋Š” ์ตœ๋Œ€ N๋ฒˆ ํ˜ธ์ถœ๋  ์ˆ˜ ์žˆ์œผ๋ฉฐ
13+
๊ฐ ์žฌ๊ท€ ํ•จ์ˆ˜์—์„œ๋Š” ์ •๋ ฌํ•˜์—ฌ ์„ธํŠธ์— ์ถ”๊ฐ€ํ•˜๋Š” ๊ฒฝ์šฐ
14+
O(N log N)์ด ์†Œ์š”๋˜๊ณ ,
15+
N๊ฐœ์˜ ์›์†Œ์— ๋Œ€ํ•ด for๋ฌธ์„ ๋ฐ˜๋ณตํ•œ๋‹ค.
16+
๋”ฐ๋ผ์„œ O(N^2 log N)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ ์†Œ์š”๋œ๋‹ค.
17+
18+
Space Complexity:
19+
O(N):
20+
์ตœ์•…์˜ ๊ฒฝ์šฐ answer set์— ๋Œ€๋žต N๊ฐœ์˜ tuple์ด ์ €์žฅ๋œ๋‹ค.
21+
๋”ฐ๋ผ์„œ O(N)์˜ ๊ณต๊ฐ„๋ณต์žก๋„๊ฐ€ ์†Œ์š”๋œ๋‹ค.
22+
"""
23+
candidates.sort() # O(N log N)
24+
answer_set = set()
25+
26+
27+
def dfs(n, arr):
28+
if n == 0:
29+
answer_set.add(tuple(sorted(arr))) # O(N log N)
30+
return
31+
32+
for candidate in candidates: # O(N)
33+
if n >= candidate:
34+
arr.append(candidate)
35+
dfs(n - candidate, arr)
36+
arr.pop()
37+
38+
39+
dfs(target, []) # O(N)
40+
answer = list(answer_set)
41+
return answer

0 commit comments

Comments
ย (0)