原网站为https://leetcode.com/problems/target-sum/description/
一、题目
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:
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.
二、代码
class Solution {
public:
int count;
map<int, int> sum;
int findTargetSumWays(vector<int>& nums, int S) {
sum.insert(pair<int, int>(nums[0], 1));
if (sum.count(-nums[0])) sum[-nums[0]] += 1;
else sum.insert(pair<int, int>(-nums[0], 1));
for (int i = 2; i <= nums.size(); i++) {
map<int, int> tmp = sum;
sum.clear();
for (map<int, int>::iterator it = tmp.begin(); it != tmp.end(); ++it) {
int f1 = (*it).first + nums[i - 1];
int f2 = (*it).first - nums[i - 1];
if (sum.count(f1)) sum[f1] += (*it).second;
else sum.insert(pair<int, int>(f1, (*it).second));
if (sum.count(f2)) sum[f2] += (*it).second;
else sum.insert(pair<int, int>(f2, (*it).second));
}
}
if (sum.count(S)) return sum[S];
else return 0;
}
};