队列&栈//目标和

给定一个非负整数数组,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);
    }
};

猜你喜欢

转载自blog.csdn.net/strawqqhat/article/details/83990882