-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3_cansum.py
More file actions
27 lines (21 loc) · 973 Bytes
/
3_cansum.py
File metadata and controls
27 lines (21 loc) · 973 Bytes
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
# Return a boolean indicating if the targetsum can be generated by the numbers
# in the array numbers. Assume all numbers in array are positive and you can
# reuse the numbers as many times as you wish.
# let n = len(numbers) and m = targetsum
# O(n^m) in time and O(m) in space before memoisation. In general, time will be exponential
# --> (branching factor) ^ (height of tree).
# O(n*m) in time and O(m) in space after memoisation
def cansum(targetsum, numbers, memo = None):
if memo is None: memo = {} # don't use mutables in function definition for python!!
if targetsum == 0: return True
if targetsum < 0: return False
if targetsum in memo: return memo[targetsum]
for num in numbers:
remainder = targetsum - num
if cansum(remainder, numbers, memo) == True:
memo[targetsum] = True
return True
memo[targetsum] = False
return False
print(cansum(7,[5,3,4]))
print(cansum(300,[7,14]))