python实现一个简单的动态规划的demo?

bluesky1年前 ⋅ 1005 阅读
答: 
# 动态规划示例
def max_value(weight, values, capacity): 
    n = len(weight)   # 计算物品个数
    dp = [[0 for _ in range(capacity+1)] for _ in range(n+1)]  # 初始化二维数组
    for i in range(1, n+1):
        for j in range(1, capacity+1 ):
            if weight[i-1] > j:
                dp[i][j] = dp[i-1][j]
            else:
                dp[i][j] = max(values[i-1] + dp[i-1][j - weight[i-1]], dp[i-1][j] )
    return dp[n][capacity]

# 测试用例
weight = [2, 2, 6, 5, 4] # 物品的重量
values = [6, 3, 5, 4, 6] # 物品的价值
capacity = 10 # 总容量
print('最大物品价值为:', max_value(weight, values, capacity))

全部评论: 0

    相关推荐