494. Target Sum

来源:互联网 发布:全天时时彩计划数据 编辑:程序博客网 时间:2024/05/29 17:50

  • Total Accepted: 16739 
  • Total Submissions: 38242 
  • Difficulty: Medium
  • Contributors: kevin.xinzhao@gmail.com

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: 5Explanation: -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:

  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];    }};


0 0
原创粉丝点击