Skip to content

Commit db5675a

Browse files
author
changmuk.im
committed
SAVE
1 parent 06de0a4 commit db5675a

File tree

1 file changed

+29
-5
lines changed

1 file changed

+29
-5
lines changed

combination-sum/EGON.py

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
class Solution:
77
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
8-
return self.solveWithDFS(candidates, target)
8+
return self.solveWithBackTracking(candidates, target)
99

1010
"""
1111
Runtime: 2039 ms (Beats 5.01%)
@@ -37,12 +37,36 @@ def solveWithDFS(self, candidates: List[int], target: int) -> List[List[int]]:
3737
return result
3838

3939
"""
40-
Runtime: ?
41-
42-
Memory: ?
40+
Runtime: 58 ms (Beats 32.30%)
41+
42+
- candidates 정렬에 O(log c)
43+
- 첫 depte에서 dfs 함수 호출에 O(c)
44+
- 그 후 candidates의 길이에 비례해서 재귀적으로 dfs를 호출하는데 O(c)
45+
- lower_bound_idx에 따라 range가 감소하기는 하나 일단은 비례 O(c')
46+
> O(log c) + O(c * c') ~= O(c * c), 단 c' <= c 이므로 이 복잡도는 upper bound
47+
Memory: 16.59 MB (Beats 75.00%)
48+
- result를 제외하고 모두 nonlocal 변수를 call by reference로 참조
49+
- dfs 함수 호출마다 메모리가 증가하는데, 호출횟수는 candidates의 길이에 비례 O(c)
50+
- lower_bound_idx에 따라 range가 감소하기는 하나 일단은 비례
51+
> O(c), 단 이 복잡도는 upper bound
4352
"""
4453
def solveWithBackTracking(self, candidates: List[int], target: int) -> List[List[int]]:
45-
return []
54+
def dfs(stack: List[int], sum: int, lower_bound_idx: int):
55+
nonlocal result, candidates, target
56+
57+
if target < sum:
58+
return
59+
elif sum < target:
60+
for idx in range(lower_bound_idx, len(candidates)):
61+
dfs(stack + [candidates[idx]], sum + candidates[idx], idx)
62+
else: # target == sum
63+
result.append(stack)
64+
return
65+
66+
result = []
67+
candidates.sort()
68+
dfs([], 0, 0)
69+
return result
4670

4771

4872
class _LeetCodeTestCases(TestCase):

0 commit comments

Comments
 (0)