cs: add «494. Target Sum»
URL: https://leetcode.com/problems/target-sum/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
9e974ce0d6
commit
b67d43c82e
1 changed files with 28 additions and 0 deletions
28
cs/target-sum.cs
Normal file
28
cs/target-sum.cs
Normal file
|
@ -0,0 +1,28 @@
|
|||
using System.Linq;
|
||||
|
||||
public class Solution {
|
||||
public int FindTargetSumWays(int[] nums, int target) {
|
||||
var total = nums.Sum();
|
||||
|
||||
var dp = new int[2 * total + 1];
|
||||
dp[nums[0] + total] = 1;
|
||||
dp[-nums[0] + total] += 1;
|
||||
|
||||
for (int i = 1; i < nums.Length; ++i) {
|
||||
var next = new int[2 * total + 1];
|
||||
|
||||
for (int sum = -total; sum <= total; ++sum) {
|
||||
if (dp[sum + total] <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
next[sum + nums[i] + total] += dp[sum + total];
|
||||
next[sum - nums[i] + total] += dp[sum + total];
|
||||
}
|
||||
|
||||
dp = next;
|
||||
}
|
||||
|
||||
return Math.Abs(target) > total ? 0 : dp[target + total];
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue