leetcode-494-Target Sum

Error:
cannot solve it.

Now I need to transform the idea to dp, not just limit to DFS/BFS, backtracking, recursion.

Here the transform equation is:

dp[i][j] = dp[i – 1][j – nums[i – 1]] + dp[i – 1][j + nums[i – 1]];
where, dp[i][j] means the ways of get result j in the first i – 1
number init: dp[0][0] = 1. Define i = 0 as empty.

But since in the array, we do not have the negative index, so we need to transform it to double size, i.e. 2 * sum + 1.(btw, we need to accumulate the result of entire array firstly.)

And now in two for loop, we use the push pattern instead of pull pattern:
i.e. transfer the equation above to:

dp[i][j – nums[i – 1]] += dp[i – 1][j]
dp[i][j + nums[i – 1]] += dp[i – 1][j]

点赞