[leetcode]Target Sum
链接:https://leetcode.com/problems/target-sum/description/
Question
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
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.
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.
Solution
class Solution {
public:
#define offset 2010
int findTargetSumWays(vector<int>& nums, int S) {
if (S > 1000) return 0;
int size = nums.size();
vector<vector<int> > dp;
dp.resize(size+1, vector<int>());
for (int i = 0; i <= size; i++) dp[i].resize(5000, 0);
if (nums[0] != 0) dp[1][-nums[0]+offset] = dp[1][nums[0]+offset] = 1;
else dp[1][0+offset] = 2;
for (int i = 2; i <= size; i++) {
for (int j = -1000; j <= 1000; j++) {
dp[i][j+offset] = dp[i-1][j+nums[i-1]+offset]+dp[i-1][j-nums[i-1]+offset];
}
}
return dp[size][S+offset];
}
};
思路:这道题用第二维模拟加的总和,记得加一个offset,因为相减可能会小于0。