1. 题目描述
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.
【翻译过来】:给了一个非负数的矩阵,里面的元素是[a0, a1, a2……]和一个目标值S,现在要在这些元素之间加入+或者-,使得里面的元素之间运算结果能够等于目标值S,求一共有多少种加入+或者-的方法。
2. 样例
Input: nums is [1, 1, 1, 1, 1], S is 3.
Output: 5
Explanation:
-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3
There are 5 ways to assign symbols to make the sum of nums be target 3.
3. 分析
拿到题目之后,即可判断出是自己不熟悉的动态规划类问题。表面上来看是在数组元素中间插入+或者-使得数组元素运算等于目标值,实际上对这个问题进行变换,可以将问题简化。
【变换】:
- 假设原数组为S,目标值为target,那么原数组必然可以分成两个部分,一个部分里面的元素前面需要加-,即运算的时候应该是做减法,另一个部分里面的元素前面需要加+,即运算的时候应该是做加法;
- 我们将做加法部分的数组记为P,做减法部分的数组记为N,举个例子,例如S = {1,2,3,