一、题目描述
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.
二、主要思想
设所有正数和为sum_p,所有负数的绝对值之和为sum_n,所有数的绝对值之和为sum,则由题目可知sum_p-sum_n=target。两边同时加sum,则等式为sum_p=(target+sum_n)/2;所以当(target+sum_n)/2为奇数时,不存在解。设数组dp[i]表示和为i的方案的个数。当和为0时,只有一种方案。遍历数组的每一个数,j从需要的最大值sum_p到读入的元素nums[j],逐个遍历j,状态转移方程为dp[j]+=dp[j-nums[i]],即不算nums[i]这个元素时dp[j]的值(也就是方案数量)加和为j-nums[i]的方案的数量。注意j从最大值sum_p开始,从大到小取值。
三、代码实现
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
int sum=0;
for(int i=0;i<nums.size();i++){
sum+=nums[i];
}
if((sum+S)%2==1) return 0;
if(S>sum) return 0;
int sum_p=(sum+S)/2;
vector<int> dp(sum_p+1);//dp[i]表示和为i的方案的个数
dp[0]=1;
for(int i=0;i<nums.size();i++){
for(int j=sum_p;j>=nums[i];j--){//j代表和
dp[j]+=dp[j-nums[i]];
}
}
return dp[sum_p];
}
};