forked from LeetCode-in-Net/LeetCode-in-Net
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
44 lines (41 loc) · 1.3 KB
/
Solution.cs
File metadata and controls
44 lines (41 loc) · 1.3 KB
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
37
38
39
40
41
42
43
44
namespace LeetCodeNet.G0401_0500.S0494_target_sum {
// #Medium #Array #Dynamic_Programming #Backtracking #Big_O_Time_O(n*(sum+s))_Space_O(n*(sum+s))
// #2025_06_16_Time_6_ms_(85.88%)_Space_45.47_MB_(56.49%)
using System;
using System.Collections.Generic;
public class Solution {
public int FindTargetSumWays(int[] nums, int s) {
int sum = 0;
s = Math.Abs(s);
foreach (int num in nums) {
sum += num;
}
// Invalid s, just return 0
if (s > sum || (sum + s) % 2 != 0) {
return 0;
}
int[][] dp = new int[(sum + s) / 2 + 1][];
for (int i = 0; i < dp.Length; i++) {
dp[i] = new int[nums.Length + 1];
}
dp[0][0] = 1;
// empty knapsack must be processed specially
for (int i = 0; i < nums.Length; i++) {
if (nums[i] == 0) {
dp[0][i + 1] = dp[0][i] * 2;
} else {
dp[0][i + 1] = dp[0][i];
}
}
for (int i = 1; i < dp.Length; i++) {
for (int j = 0; j < nums.Length; j++) {
dp[i][j + 1] += dp[i][j];
if (nums[j] <= i) {
dp[i][j + 1] += dp[i - nums[j]][j];
}
}
}
return dp[(sum + s) / 2][nums.Length];
}
}
}