mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Merge pull request #2102 from fwqaaq/patch-23
Update 背包问题理论基础完全背包.md about rust
This commit is contained in:
@ -426,6 +426,43 @@ object Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Rust:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl Solution {
|
||||||
|
// 先遍历物品
|
||||||
|
fn complete_pack() {
|
||||||
|
let (goods, bag_size) = (vec![(1, 15), (3, 20), (4, 30)], 4);
|
||||||
|
let mut dp = vec![0; bag_size + 1];
|
||||||
|
for (weight, value) in goods {
|
||||||
|
for j in weight..=bag_size {
|
||||||
|
dp[j] = dp[j].max(dp[j - weight] + value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
println!("先遍历物品:{}", dp[bag_size]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 先遍历背包
|
||||||
|
fn complete_pack_after() {
|
||||||
|
let (goods, bag_size) = (vec![(1, 15), (3, 20), (4, 30)], 4);
|
||||||
|
let mut dp = vec![0; bag_size + 1];
|
||||||
|
for i in 0..=bag_size {
|
||||||
|
for (weight, value) in &goods {
|
||||||
|
if i >= *weight {
|
||||||
|
dp[i] = dp[i].max(dp[i - weight] + value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
println!("先遍历背包:{}", dp[bag_size]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_complete_pack() {
|
||||||
|
Solution::complete_pack();
|
||||||
|
Solution::complete_pack_after();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
|
Reference in New Issue
Block a user