forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.rs
33 lines (27 loc) · 854 Bytes
/
Solution2.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 m = (sum >> 1) as usize;
// Here dp[i] means if it can be sum up to `i` for all the number we've traversed through so far
// Which is actually compressing the 2-D dp vector to 1-D
let mut dp: Vec<bool> = vec![false; m + 1];
// Initialize the dp vector
dp[0] = true;
// Begin the actual dp process
for e in &nums {
// For every num in nums vector
for i in (*e as usize..=m).rev() {
// Update the current status
dp[i] |= dp[i - (*e as usize)];
}
}
dp[m]
}
}