mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Update 背包理论基础01背包-2.md
This commit is contained in:
@ -246,25 +246,46 @@ int main() {
|
|||||||
|
|
||||||
|
|
||||||
### Python
|
### Python
|
||||||
|
无参版
|
||||||
```python
|
```python
|
||||||
def test_1_wei_bag_problem():
|
def test_1_wei_bag_problem():
|
||||||
weight = [1, 3, 4]
|
weight = [1, 3, 4]
|
||||||
value = [15, 20, 30]
|
value = [15, 20, 30]
|
||||||
bag_weight = 4
|
bagWeight = 4
|
||||||
# 初始化: 全为0
|
|
||||||
dp = [0] * (bag_weight + 1)
|
|
||||||
|
|
||||||
# 先遍历物品, 再遍历背包容量
|
# 初始化
|
||||||
for i in range(len(weight)):
|
dp = [0] * (bagWeight + 1)
|
||||||
for j in range(bag_weight, weight[i] - 1, -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])
|
dp[j] = max(dp[j], dp[j - weight[i]] + value[i])
|
||||||
|
|
||||||
print(dp)
|
print(dp[bagWeight])
|
||||||
|
|
||||||
|
|
||||||
test_1_wei_bag_problem()
|
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
|
||||||
```go
|
```go
|
||||||
func test_1_wei_bag_problem(weight, value []int, bagWeight int) int {
|
func test_1_wei_bag_problem(weight, value []int, bagWeight int) int {
|
||||||
|
Reference in New Issue
Block a user