给定一个非负整数数组,a1, a2, …, an, 和一个目标数,S。现在你有两个符号 + 和 -。对于数组中的任意一个整数,你都可以从 + 或 -中选择一个符号添加在前面。
返回可以使最终数组和为目标数 S 的所有添加符号的方法数。
示例:
输入:nums: [1, 1, 1, 1, 1], S: 3
输出:5
解释:
-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
一共有5种方法让最终目标和为3。
提示:
数组非空,且长度不会超过 20 。
初始的数组的和不会超过 1000 。
保证返回的最终结果能被 32 位整数存下。
dp[i][j]代表前i个数得到j的种类数。
class Solution {
public:
static const int maxn = 2e3 + 10;
static const int ext = 1e3;
int dp[maxn][maxn];
int findTargetSumWays(vector<int>& nums, int s) {
dp[0][nums[0] + ext]++;
dp[0][ext-nums[0]]++;
for(int i = 1; i < nums.size(); i++) {
for(int j = -ext; j <= ext; j++) {
if(j - nums[i] + ext >= 0)
dp[i][j + ext] += dp[i - 1][j - nums[i] + ext];
if(j + nums[i] + ext <= 2e3)
dp[i][j + ext] += dp[i - 1][j + nums[i] + ext];
}
}
return abs(s) > ext ? 0 : dp[nums.size() - 1][s + ext];
}
};