Created
September 10, 2020 22:02
-
-
Save dongr0510/4c39b29e843a87a754a48e1d034cc490 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def solve_knapsack(profits, weights, capacity): | |
dp = [[-1 for _ in range(capacity+1)] for _ in range(len(profits))] | |
return solve_knapsack_recursive(dp, profits, weights, capacity, 0) | |
def solve_knapsack_recursive(dp, profits, weights, capacity, currentIndex): | |
n = len(profits) | |
# base checks | |
if capacity <= 0 or n == 0 or len(weights) != n or currentIndex >= n: | |
return 0 | |
# check if we have not already processed a similar sub-problem | |
if dp[currentIndex][capacity] == -1: | |
# recursive call after choosing the items at the currentIndex, note that we | |
# recursive call on all items as we did not increment currentIndex | |
profit1 = 0 | |
if weights[currentIndex] <= capacity: | |
profit1 = profits[currentIndex] + solve_knapsack_recursive( | |
dp, profits, weights, capacity - weights[currentIndex], currentIndex) | |
# recursive call after excluding the element at the currentIndex | |
profit2 = solve_knapsack_recursive( | |
dp, profits, weights, capacity, currentIndex + 1) | |
dp[currentIndex][capacity] = max(profit1, profit2) | |
return dp[currentIndex][capacity] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment