leetcode[494]:Target Sum

来源:互联网 发布:ubuntu游客创建新用户 编辑:程序博客网 时间:2024/06/05 11:48

【原题】
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];    }}
0 0
原创粉丝点击