简体   繁体   中英

Knapsack Problem - how to get the remaining capacity

I am trying to practice my python skills, so I tried to "play" with Knapsack problem.

I used this algorithm

 def knapSack(W, wt, val, n): if n == 0 or W == 0: return 0 if (wt[n-1] > W): return knapSack(W, wt, val, n-1) else: return max( val[n-1] + knapSack( W-wt[n-1], wt, val, n-1), knapSack(W, wt, val, n-1))

I cant figure out how to count the remaining capacity at the end, for example, if my val list is [4,2,1,5,3] and the weights are [3,5,1,2,4] and my capacity(W) is 4, so it will return 6 and the remaining capacity will be 1 how can I get this 1?

thanks!

Memorization Technique (an extension of recursive approach). This method is basically an extension to the recursive approach so that we can overcome the problem of calculating redundant cases and thus increased complexity. We can solve this problem by simply creating a 2-D array that can store a particular state (n, w) if we get it the first time. Now if we come across the same state (n, w) again instead of calculating it in exponential complexity we can directly return its result stored in the table in constant time. This method gives an edge over the recursive approach in this aspect.

val = [4,2,1,5,3] 
wt = [3,5,1,2,4]] 
W = 4
n = len(val) 


t = [[-1 for i in range(W + 1)] for j in range(n + 1)] 

def knapsack(wt, val, W, n): 

    if n == 0 or W == 0: 
        return 0
    if t[n][W] != -1: 
        return t[n][W] 

    if wt[n-1] <= W: 
        t[n][W] = max( 
            val[n-1] + knapsack( 
                wt, val, W-wt[n-1], n-1), 
              knapsack(wt, val, W, n-1)) 
        return t[n][W] 
    elif wt[n-1] > W: 
        t[n][W] = knapsack(wt, val, W, n-1) 
        return t[n][W]

Please try this!

maybe this can help! I'm here using memoization

def knapsack(n, W):
    """Recursive solution"""
    arr = [[None for _ in range(W+1)] for _ in range(n+1)]

    if arr[n][W] != None: return arr[n][W]
    if n == 0 or W == 0:
        res = 0
    elif weights[n-1] > W:
        res = knapsack(n-1, W)
    else:
        tmp1 = knapsack(n-1, W)
        tmp2 = weights[n-1] + knapsack(n-1, W-weights[n-1])
        res = max(tmp1, tmp2)
    arr[n][W] = res
    return arr[n][W]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM