From e6ad637e6475c73766f401b052a1c523d171d059 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Fri, 28 Apr 2023 18:50:56 +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-2.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/背包理论基础01背包-2.md | 28 ++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/背包理论基础01背包-2.md b/problems/背包理论基础01背包-2.md index baa4107f..1ce90440 100644 --- a/problems/背包理论基础01背包-2.md +++ b/problems/背包理论基础01背包-2.md @@ -406,6 +406,34 @@ object Solution { } ``` +### Rust + +```rust +pub struct Solution; + +impl Solution { + pub fn wei_bag_problem2(weight: Vec, value: Vec, bag_size: usize) -> usize { + let mut dp = vec![0; bag_size + 1]; + for i in 0..weight.len() { + for j in (weight[i]..=bag_size).rev() { + if j >= weight[i] { + dp[j] = dp[j].max(dp[j - weight[i]] + value[i]); + } + } + } + dp[dp.len() - 1] + } +} + +#[test] +fn test_wei_bag_problem2() { + println!( + "{}", + Solution::wei_bag_problem1(vec![1, 3, 4], vec![15, 20, 30], 4) + ); +} +``` +