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.


解题思路:因为数组长度比较小,直接可以用dfs暴力搜索。效率不高,但是代码简洁优美。
class Solution {
public:
    void dfs(vector<int>& nums,int depth,int sum,int S){
        if(depth==nums.size()){
            if(sum==S)count++;
            return ;
        }
        dfs(nums,depth+1,sum+nums[depth],S);
        dfs(nums,depth+1,sum-nums[depth],S);
    }
    int findTargetSumWays(vector<int>& nums, int S) {
        dfs(nums,0,0,S);
        return count;
    }
private:
    int count;
};

解法2:动态规划。具体思路如下:https://discuss.leetcode.com/topic/76243/java-15-ms-c-3-ms-o-ns-iterative-dp-solution-using-subset-sum-with-explanation

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

 

posted @ 2017-02-26 22:25  Tsunami_lj  阅读(844)  评论(0编辑  收藏  举报