Can Sum
Brute force
def can_sum_brute(target: int, numbers: list[int]) -> bool:
"""
Time complexity: O(N^M)
Time complexity will depend on two factors:
- how big is value of target (M)
- and the number of items in numbers (N).
In the algorigthm, we explore all the available solutions by iterating
the available "numbers" to decrease the value of the target.
Then, the branching factor will be N and, in the worst scenario,
we will explore these M options up to M times.
Space complexity: O(M)
The height of the recursion tree will depend on target value.
Thus, it will depend on M.
"""
if target == 0:
return True
if target < 0:
return False
for number in numbers:
current = target - number
result = can_sum_brute(current, numbers)
if result:
return result
return FalseMemoization
Tabulation
Last updated
Was this helpful?