diff --git a/problems/背包理论基础01背包-2.md b/problems/背包理论基础01背包-2.md index 3b798334..d481e044 100644 --- a/problems/背包理论基础01背包-2.md +++ b/problems/背包理论基础01背包-2.md @@ -246,25 +246,46 @@ int main() { ### Python +无参版 ```python def test_1_wei_bag_problem(): weight = [1, 3, 4] value = [15, 20, 30] - bag_weight = 4 - # 初始化: 全为0 - dp = [0] * (bag_weight + 1) + bagWeight = 4 - # 先遍历物品, 再遍历背包容量 - for i in range(len(weight)): - for j in range(bag_weight, weight[i] - 1, -1): - # 递归公式 + # 初始化 + dp = [0] * (bagWeight + 1) + for i in range(len(weight)): # 遍历物品 + for j in range(bagWeight, weight[i] - 1, -1): # 遍历背包容量 dp[j] = max(dp[j], dp[j - weight[i]] + value[i]) - print(dp) + print(dp[bagWeight]) + test_1_wei_bag_problem() ``` +有参版 +```python +def test_1_wei_bag_problem(weight, value, bagWeight): + # 初始化 + dp = [0] * (bagWeight + 1) + for i in range(len(weight)): # 遍历物品 + for j in range(bagWeight, weight[i] - 1, -1): # 遍历背包容量 + dp[j] = max(dp[j], dp[j - weight[i]] + value[i]) + return dp[bagWeight] + + +if __name__ == "__main__": + + weight = [1, 3, 4] + value = [15, 20, 30] + bagweight = 4 + + result = test_1_wei_bag_problem(weight, value, bagweight) + print(result) + +``` ### Go ```go func test_1_wei_bag_problem(weight, value []int, bagWeight int) int {