harishv7
1/9/2018 - 3:50 PM

0-1 Knapsack - Top Down

0-1 Knapsack - Top Down

# with top-down dp
def knap_sack_top_down(w, weights, values, n):
    if(store[n-1][w] is not None):
        return store[n-1][w]
        
    result = None

    if(n == 0 or w == 0):
        result = 0
    elif(weights[n-1] > w):
        result = knap_sack_top_down(w, weights, values, n-1)
    else:
        result = max(values[n-1] + knap_sack_top_down(w - weights[n-1], weights, values, n-1),
                    knap_sack_top_down(w, weights, values, n-1))
    store[n-1][w] = result
    return result

values = [60, 100, 120]
weights = [10, 20, 30]
w = 50
n = len(values)

store = [[None for x in range(w+1)] for x in range(n+1)]
print(knap_sack_top_down(w, weights, values, n))
# result is 220