You are given a list of non-negative integers, a1, a2, …, an, and a target, S. Now you have 2 symbols +
and -
. For each integer, you should choose one from +
and -
as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.
Example 1:
1 | Input: nums is [1, 1, 1, 1, 1], S is 3. |
Note:
- The length of the given array is positive and will not exceed 20.
- The sum of elements in the given array will not exceed 1000.
- Your output answer is guaranteed to be fitted in a 32-bit integer.
暴力破解
1 | class Solution { |
自顶向下的记忆化搜索
这里会涉及到负值,如何处理呢?加上可能的最小值的负数,进行偏移.
1 | class Solution { |
自底向上
dp[i][j]表示到第i个元素,组成的和为j的方法数.
dp[i][sum + nums[i]] = dp[i][sum + nums[i]] + dp[i-1][sum]