首页 > 学院 > 开发设计 > 正文

leetcode[494]:Target Sum

2019-11-08 03:19:22
字体:
来源:转载
供稿:网友

【原题】 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]; }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表