Update 背包理论基础01背包-1.md about rust

This commit is contained in:
fwqaaq
2023-04-28 18:30:16 +08:00
committed by GitHub
parent f97940758e
commit 14c25f2eef

View File

@ -573,6 +573,39 @@ object Solution {
} }
``` ```
### Rust
```rust
pub struct Solution;
impl Solution {
pub fn wei_bag_problem1(weight: Vec<usize>, value: Vec<usize>, bag_size: usize) -> usize {
let mut dp = vec![vec![0; bag_size + 1]; weight.len()];
for j in weight[0]..=weight.len() {
dp[0][j] = value[0];
}
for i in 1..weight.len() {
for j in 0..=bag_size {
match j < weight[i] {
true => dp[i][j] = dp[i - 1][j],
false => dp[i][j] = dp[i - 1][j].max(dp[i - 1][j - weight[i]] + value[i]),
}
}
}
dp[weight.len() - 1][bag_size]
}
}
#[test]
fn test_wei_bag_problem1() {
println!(
"{}",
Solution::wei_bag_problem1(vec![1, 3, 4], vec![15, 20, 30], 4)
);
}
```
<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">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/> <img src="../pics/网站星球宣传海报.jpg" width="1000"/>