Skip to content

Commit 6e19022

Browse files
committed
solve combination sum
1 parent b8b67cf commit 6e19022

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

combination-sum/evan.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
6+
def backtrack(remain, combination, candidateIndex):
7+
if remain == 0:
8+
# if we reach the target, add the combination to the result
9+
result.append(list(combination))
10+
return
11+
elif remain < 0:
12+
# if we exceed the target, no need to proceed
13+
return
14+
15+
for i in range(candidateIndex, len(candidates)):
16+
# add the number to the current combination
17+
combination.append(candidates[i])
18+
# continue the exploration with the current number
19+
backtrack(remain - candidates[i], combination, i)
20+
# backtrack by removing the number from the combination
21+
combination.pop()
22+
23+
result = []
24+
backtrack(target, [], 0)
25+
26+
return result
27+
28+
29+
# Time Complexity: O(N^(target / min(candidates)))
30+
# The time complexity depends on:
31+
# - N: The number of candidates (branching factor at each level).
32+
# - target: The target sum we need to achieve.
33+
# - min(candidates): The smallest element in candidates influences the maximum depth of the recursion tree.
34+
# In the worst case, we branch N times at each level, and the depth can be target / min(candidates).
35+
# Therefore, the overall time complexity is approximately O(N^(target / min(candidates))).
36+
37+
# Space Complexity: O(target / min(candidates))
38+
# The space complexity is influenced by the maximum depth of the recursion tree:
39+
# - target: The target sum we need to achieve.
40+
# - min(candidates): The smallest element in candidates influences the maximum depth.
41+
# The recursion stack can go as deep as target / min(candidates), so the space complexity is O(target / min(candidates)).
42+
# Additionally, storing the results can take significant space, but it depends on the number of valid combinations found.

0 commit comments

Comments
 (0)