0% completed
Problem Challenge 2: Target Sum (hard)
.....
.....
.....
Anonymous
· 4 years ago
This method cannot past the test case [0,0,0,0,0,0,0,0,1] S = 1 . Is there another solution?
Anonymous
· 4 years ago
Can you share the Target Sum solution with memoization?
Anonymous
· 5 years ago
This is the wrong solution to the problem. The right solution is below,
public int findTargetSumWays(int[] nums, int S) { int total = Arrays.stream(nums).sum(); int[] dp = new int[2 * total + 1]; dp[nums[0] + total] = 1; dp[-nums[0] + total] += 1;
for (int i = 1; i < nums.length; i++) { int[] next = new int[2 * total + 1]; for (int sum = -total; sum 0) { next[sum + nums[i] + total] += dp[sum + total]; next[sum - nums[i] + total] += dp[sum + total]; } } dp = next; }
return Math.abs(S) > total ? 0 : dp[S + total]; }
Reading Progress
0%