@@ -46,21 +46,17 @@ def knapsack_recur(capacity: int, counter: int) -> int:
4646 # If weight of the nth item is more than Knapsack of capacity,
4747 # then this item cannot be included in the optimal solution,
4848 # else return the maximum of two cases:
49- # (1) not included
50- # (2) nth item included one or more times (0-N), if allow_repetition is True
49+ # (1) nth item included one or more times (0-N), if allow_repetition is True
5150 # nth item included only once (0-1), if allow_repetition is False
51+ # (2) not included
5252 if weights [counter - 1 ] > capacity :
5353 return knapsack_recur (capacity , counter - 1 )
5454 else :
55+ left_capacity = capacity - weights [counter - 1 ]
56+ new_value_included = values [counter - 1 ] + knapsack_recur (
57+ left_capacity , not allow_repetition ? counter - 1 : counter
58+ )
5559 without_new_value = knapsack_recur (capacity , counter - 1 )
56- if allow_repetition :
57- new_value_included = values [counter - 1 ] + knapsack_recur (
58- capacity - weights [counter - 1 ], counter
59- )
60- else :
61- new_value_included = values [counter - 1 ] + knapsack_recur (
62- capacity - weights [counter - 1 ], counter - 1
63- )
6460 return max (new_value_included , without_new_value )
6561
6662 return knapsack_recur (capacity , counter )
0 commit comments