diff --git a/problems/背包理论基础01背包-1.md b/problems/背包理论基础01背包-1.md index c45fc3d3..c2525248 100644 --- a/problems/背包理论基础01背包-1.md +++ b/problems/背包理论基础01背包-1.md @@ -573,6 +573,39 @@ object Solution { } ``` +### Rust + +```rust +pub struct Solution; + +impl Solution { + pub fn wei_bag_problem1(weight: Vec, value: Vec, 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) + ); +} +``` +