494. Target Sum

题目:

You are given an integer array nums and an integer target.

You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.

  • For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1".

Return the number of different expressions that you can build, which evaluates to target.

Example 1:

Input: nums = [1,1,1,1,1], target = 3
Output: 5
Explanation: There are 5 ways to assign symbols to make the sum of nums be target 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
+1 + 1 + 1 + 1 - 1 = 3

Example 2:

Input: nums = [1], target = 1
Output: 1

Constraints:

  • 1 <= nums.length <= 20
  • 0 <= nums[i] <= 1000
  • 0 <= sum(nums[i]) <= 1000
  • -1000 <= target <= 1000

思路1:

转化成dp中的背包问题,这个转化过去比较难想。首先一堆数字,里面肯定有一堆要是加上负号的,称为A,一堆要是正的,称为B,A+B=sum,即数组总和,sum一定是正数,因为题目给的数组里面值都大于等于0。那么我们其实我们要做的就是使B - A = target即可,代入为 B - (sum - B) = target,这里显然sum和target都是定值,转化一下即可求出B:B = \tfrac{sum + target}{2}。这里有几个点要注意,首先如果sum+target是个奇数,那么B肯定是不成立的,应该返回0;另一个是如果target比sum还要大,那怎么都不可能达到,也要返回0。到这里已经可以转化成背包问题了,背包总重量是B,dp[ j ]表示和为 j 的方法有几种。转移公式应该是dp[j] += dp[j - nums[i]],比如我已经有了dp[3],并且当前nums[i] = 2,那么dp[5]的其中一些方法就来自于dp[5 - 2]即dp[3]。最后返回dp[B]即可。

代码1:

class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int target) {
        int sum = accumulate(begin(nums), end(nums), 0);
        target = abs(target);
        if ((sum + target) & 1 || target > sum)
            return 0;
        int bag = (sum + target) / 2;
        vector<int> f(bag + 1);
        f[0] = 1;
        for (int i = 0; i < nums.size(); i++) {
            for (int j = bag; j >= nums[i]; j--) {
                f[j] += f[j - nums[i]];
            }
        }
        return f[bag];
    }
};

思路2:

第二种方法是回溯法,因为nums长度最大为20,可以暴力搜索出来。对于nums每一位,选择无非是加上或者减去,当遍历完数组后,如果答案等于target,则记录,最后返回记录的那个值即可。

代码2:

class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int target) {
        dfs(nums, 0, 0, target);
        return count;
    }
private:
    int count = 0;
    void dfs(vector<int>& nums, int index, int cur, int target) {
        if (index == nums.size()) {
            if (cur == target)
                count++;
            return;
        } 
        dfs(nums, index + 1, cur + nums[index], target);
        dfs(nums, index + 1, cur - nums[index], target);
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值