From 0012d62724742e7492c4b06a0c55ac5305ac380f Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Tue, 9 Aug 2022 19:20:23 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200416.=E5=88=86=E5=89=B2?= =?UTF-8?q?=E7=AD=89=E5=92=8C=E5=AD=90=E9=9B=86=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0416.分割等和子集 Rust版本 --- problems/0416.分割等和子集.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0416.分割等和子集.md b/problems/0416.分割等和子集.md index 83b267ac..03eae8ef 100644 --- a/problems/0416.分割等和子集.md +++ b/problems/0416.分割等和子集.md @@ -417,7 +417,32 @@ var canPartition = function(nums) { ``` +### Rust +```Rust +impl Solution { + fn max(a: usize, b: usize) -> usize { + if a > b { a } else { b } + } + pub fn can_partition(nums: Vec) -> bool { + let nums = nums.iter().map(|x| *x as usize).collect::>(); + let mut sum = 0; + let mut dp: Vec = vec![0; 10001]; + for i in 0..nums.len() { + sum += nums[i]; + } + if sum % 2 == 1 { return false; } + let target = sum / 2; + for i in 0..nums.len() { + for j in (nums[i]..=target).rev() { + dp[j] = Self::max(dp[j], dp[j - nums[i]] + nums[i]); + } + } + if dp[target] == target { return true; } + false + } +} +``` ### C: