给定n个元素的重量和其对应的价值,将这些物品放在一个容量为W的背包中,并使得总价值最大。数组val [0 . . n - 1]和wt [0 . . n - 1],它们分别代表价值和重量。 总重量W代表背包容量,
之前也写过0-1背包问题:https://www.cnblogs.com/xiximayou/p/12004082.html
今天看到了个递归的方法,挺简洁的,记录一下:
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)) val = [60, 100, 120] wt = [10, 20, 30] W = 50 """ val=[5,4,6,2] wt=[2,4,5,3] W=8 """ n = len(val) print(knapSack(W , wt , val , n) )
输出:220
递归方法会出现子问题重复计算问题,可用以下方法解决:
def knapSack(W, wt, val, n): K = [[0 for x in range(W+1)] for x in range(n+1)] # Build table K[][] in bottom up manner for i in range(n+1): for w in range(W+1): if i==0 or w==0: K[i][w] = 0 elif wt[i-1] <= w: K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]) else: K[i][w] = K[i-1][w] return K[n][W]
参考:https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/