【LeetCode】494. Target Sum

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 ) O(2n)
  • Space complexity : O ( n ) O\left ( n \right ) O(n)
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 ) O(n(sum+s)/2)
  • Space complexity : O ( ( s u m + s ) / 2 ) O\left ( (sum+s) / 2 \right ) O((sum+s)/2)
    思路
    原题的目的是为了分成正负两个子集
正子集 - 负子集 = 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];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值