From 14c25f2eeff8e024f822485c4fbdfddcb0c3710e Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Fri, 28 Apr 2023 18:30:16 +0800 Subject: [PATCH] =?UTF-8?q?Update=20=E8=83=8C=E5=8C=85=E7=90=86=E8=AE=BA?= =?UTF-8?q?=E5=9F=BA=E7=A1=8001=E8=83=8C=E5=8C=85-1.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/背包理论基础01背包-1.md | 33 ++++++++++++++++++++++++ 1 file changed, 33 insertions(+) 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) + ); +} +``` +