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:
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:
用dfs + memo的想法来解决。
用一个map来记录对于一个子数组和一个相对应的和,有多少种方法可以计算出相对应的和。
然后进行dfs遍历,对于每一个元素,有+和-两种办法加和到总和之中,然后再进行下一步遍历。
直到遍历到数组的最后一个,只需要判断最后一个元素是否是所剩和的+/-就可。
C++
Java