【LeetCode】494. Target Sum

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zpalyq110/article/details/86659514

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.
Note:
The length of the given array is positive and will not exceed 20.
The sum of elements in the given array will not exceed 1000.
Your output answer is guaranteed to be fitted in a 32-bit integer.
Difficulty:Medium

Example:

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.

方法1:暴力递归

  • Time complexity : O ( 2 n ) O\left ( 2^n\right )
  • Space complexity : O ( n ) O\left ( n \right )
class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int S) {
        return helper(nums, 0, S);
    }
    
    int helper(vector<int>& nums, int cur, int s){
        if(cur == nums.size())
            if(s == 0) return 1;
            else return 0;
        return helper(nums, cur+1, s-nums[cur]) + helper(nums, cur+1, s+nums[cur]);
    }
};

方法2:转化问题,动态规划

  • Time complexity : O ( n ( s u m + s ) / 2 ) O\left ( n * (sum+s) / 2 \right )
  • Space complexity : O ( ( s u m + s ) / 2 ) O\left ( (sum+s) / 2 \right )
    思路
    原题的目的是为了分成正负两个子集
正子集 - 负子集 = s
正子集 - 负子集 + 正子集 + 负子集 = s + 正子集 + 负子集
2 * 正子集 = s + sum

转化问题为在nums中找和为(s+sum)/ 2的子集
动态规划可解,注意需要从大到小计算dp,避免重复利用元素。
dp[n] = dp[n-x] + dp[n-y] + ......

class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int S) {
        int sum = accumulate(nums.begin(), nums.end(), 0);
        if (sum < S || (sum + S) % 2 != 0) return 0;
        return helper(nums, (sum+S)/2);
    }
    
    int helper(vector<int>& nums, int s){
        vector<int> dp(s+1);
        dp[0] = 1;
        for(auto num : nums)
            for(int i = s; i >= num; i--) // 此处一定要从外到里计算!!!
                dp[i] += dp[i-num];
        return dp[s];
    }
};

猜你喜欢

转载自blog.csdn.net/zpalyq110/article/details/86659514
今日推荐