forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.rs
33 lines (28 loc) · 788 Bytes
/
Solution.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
impl Solution {
#[allow(dead_code)]
pub fn can_partition(nums: Vec<i32>) -> bool {
let mut sum = 0;
for e in &nums {
sum += *e;
}
if sum % 2 != 0 {
return false;
}
let n = nums.len();
let m = (sum / 2) as usize;
let mut dp: Vec<Vec<bool>> = vec![vec![false; m + 1]; n + 1];
// Initialize the dp vector
dp[0][0] = true;
// Begin the actual dp process
for i in 1..=n {
for j in 0..=m {
dp[i][j] = if (nums[i - 1] as usize) > j {
dp[i - 1][j]
} else {
dp[i - 1][j] || dp[i - 1][j - (nums[i - 1] as usize)]
};
}
}
dp[n][m]
}
}