0
点赞
收藏
分享

微信扫一扫

[leetcode] 494. 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:

  1. The length of the given array is positive and will not exceed 20.
  2. The sum of elements in the given array will not exceed 1000.
  3. Your output answer is guaranteed to be fitted in a 32-bit integer.

分析

题目的意思是:给定一个数组和一个target,可以指定每个数的正负号,然后求和等于target,求有多少种指定方式。

  • 用sum§表示被标记为正数的子集合,N表示被标记为负数的子集合,然后根据题意要满足下面的条件:

sum(P) - sum(N) = target  
sum(P) + sum(N) + sum(P) - sum(N) = target + sum(P) + sum(N)
2 * sum(P) = target + sum(nums)

nums = {1,2,3,4,5}, target=3

  • 求解nums中子集合只和为sum§的方案个数(nums中所有元素都是非负)
    给定集合nums={1,2,3,4,5}, 求解子集,使子集中元素之和等于9 = new_target = sum§ = (target+sum(nums))/2
    当前元素等于1时,dp[9] = dp[9] + dp[9-1]
    dp[8] = dp[8] + dp[8-1]

    dp[1] = dp[1] + dp[1-1]
    当前元素等于2时,dp[9] = dp[9] + dp[9-2]
    dp[8] = dp[8] + dp[8-2]

    dp[2] = dp[2] + dp[2-2]
    当前元素等于3时,dp[9] = dp[9] + dp[9-3]
    dp[8] = dp[8] + dp[8-3]

    dp[3] = dp[3] + dp[3-3]
    当前元素等于4时,

    当前元素等于5时,

    dp[5] = dp[5] + dp[5-5]
    最后返回dp[9]即是所求的解

代码

class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
int sum=accumulate(nums.begin(),nums.end(),0);
return sum<S||(S+sum) & 1 ? 0:subsetSum(nums,(sum+S)>>1);
}
int subsetSum(vector<int>& nums,int s ){
int dp[s+1]={0};
dp[0]=1;
for(int n:nums){
for(int i=s;i>=n;i--){
dp[i]+=dp[i-n];
}
}
return dp[s];
}
};

参考文献

​​494. Target Sum​​​​leetcode – 494. Target Sum【数学转化 + 动态规划】​​​​494. Target Sum​​


举报

相关推荐

0 条评论