494. Target Sum

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.

Example 1:

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.
 

Constraints:

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.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/target-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

方法一:dfs

class Solution {
    int ans = 0;
    int[] sum;
    public int findTargetSumWays(int[] nums, int S) {
        sum = Arrays.copyOf(nums, nums.length);
        for (int i = nums.length - 2; i >= 0; i--) {
            sum[i] = sum[i] + sum[i + 1];
        }
        helper(nums, S, 0, 0);
        return ans;
    }

    private void helper(int[] nums, int target, int i, int tmp) {
        if (i == nums.length) {
            if (tmp == target) {
                ans++;
            }
            return;
        }
        if (tmp + sum[i] < target) {
            return;
        }

        helper(nums, target, i + 1, tmp + nums[i]);
        helper(nums, target, i + 1, tmp - nums[i]);
    }
}

方法二:

数组中能算出目标值,肯定是一组前面是正号需要加的子集P,和一个需要减的子集M,即

sum(P) - sum(M) = target

sum(P) - sum(M) + sum(P) + sum(M) = target + sum(P) + sum(M)

2 * sum(P) = target + sum(nums)

sum(P) = (target + sum(nums)) / 2

(target + sum(nums)) / 2是一个可以直接算出来的固定值,那么我们只要求出,nums中和是P的子集有多个即可。用dp[i]表示sums中和是i的子集个数。

class Solution {
    public int findTargetSumWays(int[] nums, int S) {
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
        }
        if (S > sum || (sum + S) % 2 == 1)
            return 0;
        int target = (sum + S) / 2;
        int []dp = new int[target + 1];
        dp[0] = 1;
        for (int i = 0; i < nums.length; i++) {
            for (int j = target; j >= nums[i]; j--) {
                dp[j] = dp[j] + dp[j - nums[i]];
            }
        }
        return dp[target];
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值