-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3.3bestSum.py
85 lines (66 loc) · 2.81 KB
/
3.3bestSum.py
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#BestSum Problem
#Brute Force
def bestSum(targetSum, numbers):
#base case
if targetSum == 0: return []
if targetSum < 0: return None
shortestCombination = None
for num in numbers: # iterate through the numbers in the array for possible matches
result = bestSum(targetSum - num, numbers)
if result != None:
currentCombination = [ *result, num]
if ( shortestCombination == None or len(currentCombination) < len(shortestCombination)):
shortestCombination = currentCombination
return shortestCombination
# time complexity = O(n**m * m)
# space = O(m)
print(bestSum(100,[1,2,5,25]))
#Memoization
def bestSum(targetSum, numbers, mem = {}):
#base case
if targetSum in mem: return mem[targetSum]
if targetSum == 0: return []
if targetSum < 0: return None
shortestCombination = None
for num in numbers: # iterate through the numbers in the array for possible matches
result = bestSum(targetSum - num, numbers)
if result != None:
currentCombination = [ *result, num]
if ( shortestCombination == None or len(currentCombination) < len(shortestCombination)):
shortestCombination = currentCombination
mem[targetSum] = shortestCombination
return mem[targetSum]
# time complexity = O(n**m * m)
# space = O(m)
# Or,
# Using the dp approch
# using memoization
def bestSum(targetSum, numbers, mem = {}):
#base case
if targetSum in mem: return mem[targetSum]
if targetSum == 0: return []
if targetSum < 0: return None
mem[targetSum] = None
for num in numbers: # iterate through the numbers in the array for possible matches
result = bestSum(targetSum - num, numbers, mem)
if result != None:
currentCombination = [ *result, num]
if ( mem[targetSum] == None or len(currentCombination) < len(mem[targetSum])):
mem[targetSum] = currentCombination
return mem[targetSum]
# time complexity = O(n**m * m)
# space = O(m)
#Tabulation
def bestSum(targetSum, llist):
table = [None] * (targetSum + 1)# Create a table of (targetSum length + 1) and init with some default vlaue based on the return vlaue
table[0] = [] # Seed values by making trival sub problem. Given any array it is possible to generate 0
for i in range(targetSum +1): # iteration and the logic
if(table[i] is not None):
for j in llist:
if (i+j) <= targetSum :
current = table[i] + [j]
if table[i+j] is None or (len(table[i+j]) > len(current)): table[i+j] = current
return table[targetSum] #filter out the none in the final answer
# t = O(n*m**2)
# s = O(m**2)
print(bestSum(8,[7,8,3,1]))