Skip to content

Commit 05ecd5e

Browse files
committed
[csharp] 494. Target Sum
1 parent 619aad9 commit 05ecd5e

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

Diff for: csharp/494-Target-Sum.cs

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
public class Solution
2+
{
3+
public int FindTargetSumWays(int[] nums, int target)
4+
{
5+
return Dp(nums, target, nums.Length - 1, 0, new Dictionary<(int, int), int>());
6+
}
7+
8+
private int Dp(int[] nums, int target, int index, int sum, Dictionary<(int, int), int> memo)
9+
{
10+
if (memo.ContainsKey((index, sum))) return memo[(index, sum)];
11+
if (index < 0 && sum == target) return 1;
12+
if (index < 0) return 0;
13+
14+
var positive = Dp(nums, target, index - 1, sum + nums[index], memo);
15+
var negative = Dp(nums, target, index - 1, sum + -1 * nums[index], memo);
16+
17+
memo.Add((index, sum), positive + negative);
18+
return memo[(index, sum)];
19+
}
20+
}

0 commit comments

Comments
 (0)