题目:
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:#include<iostream> #include<vector> #include<numeric> using namespace std; class Solution { public: int findTargetSumWays(vector<int>& nums, int s) { int sum = accumulate(nums.begin(), nums.end(), 0); return sum < s || (s + sum) %2 > 0 ? 0 : subsetSum(nums, (s + sum) >> 1); } int subsetSum(vector<int>& nums, int s) { int dp[s + 1] = { 0 }; dp[0] = 1; for (int j = 0; j < nums.size(); j++ ) for (int i = s; i >= nums[j]; i--) dp[i] += dp[i - nums[j]]; return dp[s]; } }; int main() { int arr[] = {1,1,1,1,1}; vector<int> v(arr,arr+5); Solution s; cout << s.findTargetSumWays(v,3)<<endl; }
-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 = 3There 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.
翻译:
你有一个非负整数列表,A1,A2,A,A和目标,S.现在你有2个符号+和—。对于每个整数,你应该选择一个从+和-作为它的新符号。
找出分配符号使整数等于目标S的方法有多少种
例1:
输入:公司是[ 1,1,1,1,1 ],S为3。
输出:5
解释:
- 1 + 1 + 1 + 1 + 1 = 3
+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位整数。
找出分配符号使整数等于目标S的方法有多少种
例1:
输入:公司是[ 1,1,1,1,1 ],S为3。
输出:5
解释:
- 1 + 1 + 1 + 1 + 1 = 3
+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位整数。
解题思路:
1.可以将该序列arr分为正整数和负整数部分集合,分别用ps,和ng表示,那么target = ps - ng,sum表示该序列绝对值的和
2.target +sum = ps - ng +ps + ng = 2 ps;
3. 求该序列中有多少项满足 ps = (target +sum)/2
解题代码:
#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int s) {
int sum = accumulate(nums.begin(), nums.end(), 0);
return sum < s || (s + sum) %2 > 0 ? 0 : subsetSum(nums, (s + sum) >> 1);
}
int subsetSum(vector<int>& nums, int s) {
int dp[s + 1] = { 0 };
dp[0] = 1;
for (int j = 0; j < nums.size(); j++ )
for (int i = s; i >= nums[j]; i--)
dp[i] += dp[i - nums[j]];
return dp[s];
}
};
int main() {
int arr[] = {1,1,1,1,1};
vector<int> v(arr,arr+5);
Solution s;
cout << s.findTargetSumWays(v,3)<<endl;
}
解题状态: