-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.rs
36 lines (31 loc) · 1.04 KB
/
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
34
35
36
impl Solution {
#[allow(dead_code)]
pub fn find_target_sum_ways(nums: Vec<i32>, target: i32) -> i32 {
let mut sum = 0;
for e in &nums {
sum += *e;
}
// -x + (sum - x) = target <-> -2 * x + sum = target <-> 2 * x = sum - target
if sum < target || (sum - target) % 2 != 0 {
// There is no way to get any expression in this case
return 0;
}
let n = nums.len();
let m = (sum - target) / 2;
let mut dp: Vec<Vec<i32>> = vec![vec![0; m as usize + 1]; n + 1];
// Initialize the dp vector
dp[0][0] = 1;
// Begin the actual dp phase
for i in 1..=n {
for j in 0..=m as usize {
// nums[i - 1] is not included
dp[i][j] = dp[i - 1][j];
if nums[i - 1] <= (j as i32) {
// nums[i - 1] is included
dp[i][j] += dp[i - 1][j - (nums[i - 1] as usize)];
}
}
}
dp[n][m as usize]
}
}