LeetCode刷题实战494:目标和
共 2420字,需浏览 5分钟
·
2022-01-14 01:54
You are given an integer array nums and an integer target.
You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.
For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1".
Return the number of different expressions that you can build, which evaluates to target.
示例
示例 1:
输入:nums = [1,1,1,1,1], target = 3
输出:5
解释:一共有 5 种方法让最终目标和为 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
+1 + 1 + 1 + 1 - 1 = 3
示例 2:
输入:nums = [1], target = 1
输出:1
解题
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
int sum = 0;
for(int i=0;isum += nums[i];
if(abs(S) > abs(sum))
return 0;
int t = sum * 2 + 1; //注意t的取值
int len = nums.size();
vector<vector<int>> dp(len,vector<int>(t));
if(nums[0] == 0)
dp[0][sum] = 2;
else{
dp[0][sum + nums[0]] = 1;
dp[0][sum - nums[0]] = 1;
}
for(int i = 1;i < nums.size();i++)
for(int j = 0;j < t;j++){
int l = (j - nums[i]) >= 0 ? j-nums[i] : 0;
int r = (j + nums[i]) < t ? j+nums[i] : 0;
dp[i][j] = dp[i-1][l] + dp[i-1][r];
}
return dp[nums.size()-1][sum + S];
}
};