494. Target Sum

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.


解题思路:

对于一个数组nums,在增加加号或者减号之后他的和值范围是 [-sum(nums),  sum(nums)]。对于nums中的每一个数,都有加和减两种选择。得到的这两个结果再加或者减第二个数,又有4个结果。用dp[i + sum(nums)] 来记录每次操作之后使得和为i的方法数,经过一轮操作后dp[S+sum(nums)] 就是答案。

0_1485048724190_Screen Shot 2017-01-21 at 8.31.48 PM.jpg

代码:

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(S > sum || S < -sum || (S+sum)%2 != 0)
        	return 0;
        int dp[2001] = {0};
        dp[sum] = 1;
        for(int i = 0; i < nums.size(); i++){
        	int next[2001] = {0};
        	for(int j = 0; j < 2 * sum + 1; j++){
        		if(dp[j] != 0){
        			next[j - nums[i]] += dp[j];
        			next[j + nums[i]] += dp[j];
        		}
        	}
        	for(int j = 0; j < 2 * sum + 1; j++)
        	    dp[j] = next[j];
        }
        return dp[sum + S];
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值