Created
September 10, 2020 21:57
-
-
Save dongr0510/998cd84953551e7cb234d0ccca4b225c 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): | |
return solve_knapsack_recursive(profits, weights, capacity, 0) | |
def solve_knapsack_recursive(profits, weights, capacity, currentIndex): | |
n = len(profits) | |
# base checks | |
if capacity <= 0 or n == 0 or len(weights) != n or currentIndex >= n: | |
return 0 | |
# 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( | |
profits, weights, capacity - weights[currentIndex], currentIndex) | |
# recursive call after excluding the element at the currentIndex | |
profit2 = solve_knapsack_recursive( | |
profits, weights, capacity, currentIndex + 1) | |
return max(profit1, profit2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment