小白用python解决01背包问题遇到dp数组初始化问题
n = [0, 1, 5, 11, 5] num = 4 # 物品数量 Vbag = 8 # 背包体积 dp = [[0] * (Vbag + 1) for _ in range(num+1)] ap = [[0] * (Vbag + 1)] * (num + 1) print(ap == dp) # weight = n # value = weight weight = [0, 2, 3, 4, 5] value = [0, 3, 4, 5, 6] for i in range(1, num + 1): for j in range(1, Vbag + 1): if j < weight[i]: dp[i][j] = dp[i-1][j] else: dp[i][j] = max(dp[i-1][j], dp[i-1][j-weight[i]] + value[i]) print(dp, end=' ')
刷题小白的问题:
01背包问题,dp和ap两个初始化数组一模一样,print(dp == ap)都是True,但为什么这两种初始化方式最后经过后边的算法得出的结果不一样呢
用dp初始化方式得到如下正确结果:
D:\WeGameApps\anaconda\python.exe C:/Users/qwe/Desktop/深度学习与工作/代码题/动态规划/分割等和子集.py True [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 3, 3, 3, 3, 3, 3, 3], [0, 0, 3, 4, 4, 7, 7, 7, 7], [0, 0, 3, 4, 5, 7, 8, 9, 9], [0, 0, 3, 4, 5, 7, 8, 9, 10]] Process finished with exit code 0但是若用ap的初始化方式则得到下边错误的结果:
D:\WeGameApps\anaconda\python.exe C:/Users/qwe/Desktop/深度学习与工作/代码题/动态规划/分割等和子集.py True [[0, 0, 3, 4, 6, 7, 9, 10, 12], [0, 0, 3, 4, 6, 7, 9, 10, 12], [0, 0, 3, 4, 6, 7, 9, 10, 12], [0, 0, 3, 4, 6, 7, 9, 10, 12], [0, 0, 3, 4, 6, 7, 9, 10, 12]] Process finished with exit code 0有da lao知道是怎么回事儿吗?万分感激!!!!