How Sum
Brute force
def how_sum_brute(target_sum: int, numbers: list[int]):
"""
Time complexity: O(N^M * M)
Time complexity will depend on two factors:
- how big is value of target_sum (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.
Additionally, for every iteration we copy all the
elements of the solution and we add an element.
This list of elements will be bounded by M given
its lenght could be M in the worst case.
Space complexity: O(M)
The height of the recursion tree will depend on target
value. Thus, it will depend on M.
"""
if target_sum == 0:
return []
if target_sum < 0:
return None
for number in numbers:
diff = target_sum - number
result = how_sum_brute(diff, numbers)
if result is not None:
return [*result, number]
return NoneMemoization
Tabulation
Last updated
Was this helpful?