From b67d43c82e7f9b8ecfcf0d6c9893b8f8e9bf2cbe Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 26 Dec 2024 19:19:28 +0100 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=C2=AB494.=20Target=20Sum=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/target-sum/ Signed-off-by: Matej Focko --- cs/target-sum.cs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 cs/target-sum.cs diff --git a/cs/target-sum.cs b/cs/target-sum.cs new file mode 100644 index 0000000..7a7f6c4 --- /dev/null +++ b/cs/target-sum.cs @@ -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]; + } +}