队列&栈//目标和

给定一个非负整数数组,a1, a2, ..., an, 和一个目标数,S。现在你有两个符号 + 和 -。对于数组中的任意一个整数,你都可以从 + 或 -中选择一个符号添加在前面。

返回可以使最终数组和为目标数 S 的所有添加符号的方法数。

示例 1:

输入: nums: [1, 1, 1, 1, 1], S: 3
输出: 5
解释: 

-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

一共有5种方法让最终目标和为3。

注意:

  1. 数组的长度不会超过20,并且数组中的值全为正数。
  2. 初始的数组的和不会超过1000。
  3. 保证返回的最终结果为32位整数。
class Solution {
    public int findTargetSumWays(int[] nums, int S) {
        int sum = 0;
        int n = nums.length;
        for(int i = 0; i < n; i++){
            sum += nums[i];
        }
        if(S>sum||(sum+S)%2!=0)
            return 0;
        int t =(sum+S)/2;
        int[] dp = new int[t+1];
        dp[0] = 1;
        for(int i = 0; i < n; i++){
            for(int j = t; j >= nums[i]; j--){
                dp[j]+=dp[j-nums[i]];
            }
        }
        return dp[t];
    }
}

 

class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int S) {
        unordered_map<int,int> dp;
        dp[0] = 1;
        for(int num:nums){
            unordered_map<int,int> t;
            for(auto a:dp){
                int sum = a.first, cnt = a.second;
                t[sum+num]+=cnt;
                t[sum-num]+=cnt;
            }
            dp = t;
        }
        return dp[S];
    }
};
class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int S) {
        int res = 0;
        helper(nums,S,0,res);
        return res;
    }
    void helper(vector<int>& nums, int S, int start, int& res){
        if(start >= nums.size()){
            if(S == 0)
                res++;
            return ;
        }
        helper(nums, S-nums[start], start+1, res);
        helper(nums, S+nums[start], start+1, res);
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值