-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathpmjuu.py
33 lines (25 loc) Β· 1.38 KB
/
pmjuu.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from typing import List
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
def backtrack(start, target, current_combination):
# μ’
λ£ μ‘°κ±΄
if target == 0:
result.append(list(current_combination))
return
if target < 0:
return
# λ°±νΈλνΉ
for i in range(start, len(candidates)):
current_combination.append(candidates[i])
backtrack(i, target - candidates[i], current_combination) # κ°μ μμλ₯Ό μ¬λ¬ λ² μΈ μ μλλ‘ iλ₯Ό κ·Έλλ‘ λ‘λλ€.
current_combination.pop() # λμκ°μ λ€μ μλν μ μλλ‘ μμλ₯Ό μ κ±°ν©λλ€.
backtrack(0, target, [])
return result
# μκ° λ³΅μ‘λ: O(n^t)
# - ν보 리μ€νΈμμ κ° μ«μλ₯Ό μ νν μ μκΈ° λλ¬Έμ, nκ°μ ν보λ₯Ό μ¬μ©ν΄ tλ²μ νμμ ν μ μμ΅λλ€.
# - λ°λΌμ μ΅μ
μ κ²½μ° νμ νμλ O(n^t)λ‘ λ³Ό μ μμ΅λλ€.
#
# κ³΅κ° λ³΅μ‘λ: O(t)
# - μ¬κ· νΈμΆ μ€νμ κΉμ΄λ μ΅λ target κ°μΈ tμ λΉλ‘νλ―λ‘, κ³΅κ° λ³΅μ‘λλ O(t)μ
λλ€.
# - λν, νμ¬κΉμ§ μ νλ μ«μλ€μ μ‘°ν©μ μ μ₯νλ 곡κ°λ μ΅λ tκ°κΉμ§ μ μ₯νλ―λ‘, κ³΅κ° λ³΅μ‘λλ O(t)μ
λλ€.