leetcode[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.

【分析】

题意就是在每个数组元素的前面添加正负号,使得最后的代数和等于target,求共有多少种解法。

思路一:深度优先搜索(DFS)

public class Solution {
    int ret = 0;
    public int findTargetSumWays(int[] nums, int S) {
        if(nums == null || nums.length == 0) return ret;
        helper(nums,0,0,S);
        return ret;
    }
    public void helper(int[] nums,int index,int sum,int target){
        if(index == nums.length){
            if(sum==target )
            ret++;
            return ;
        }
        helper(nums,index+1,sum+nums[index],target);
        helper(nums,index+1,sum-nums[index],target);
    }
}

思路二:(动态规划)DP
加入“+”和“-”之后原数组的元素可以看成被分成了两个子集合,一个正的子集合P,另一个负的子集合N。
For example:

Given nums = [1, 2, 3, 4, 5] and target = 3 then one possible solution
is +1-2+3-4+5 = 3 Here positive subset is
P = [1, 3, 5] and negative subset is N = [2, 4]

令sum(P)表示集合P所有元素之和,sum(N)表示集合N所有元素之和

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

问题转化为求原集合中的一个子集,使得子集所有元素和满足
sum(P) = (target + sum(nums))/2
【Java】

public class Solution {
    int ret = 0;
    public int findTargetSumWays(int[] nums, int S) {
        int sum = 0;
        for (int n : nums) {
            sum+=n;
        }
        return sum<S || (sum+S)%2>0 ? 0:findSubSet(nums,(sum+S)>>>1);
    }
    public int findSubSet(int[] nums, int s) {
        int[] dp = new int[s+1];
        dp[0] = 1;//和为0只有一种
        for (int n : nums) {
            for (int i = s; i >= n; i--) {
                dp[i] += dp[i-n];
            }
        }
        return dp[s];
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值