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 = 3There 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]; }}
- leetcode[494]:Target Sum
- LeetCode 494:Target Sum
- leetcode 494 Target sum
- leetcode(494). Target Sum
- LeetCode 494 Target Sum 题解
- 【Leetcode-Medium-494】Target Sum
- LeetCode#494 Target Sum (week14)
- Leetcode 494 - Target Sum(01背包)
- LeetCode 494. Target Sum
- [LeetCode]494. Target Sum
- [leetcode]494. Target Sum
- Leetcode 494. Target Sum
- LeetCode: Target Sum
- leetCode---Target Sum
- Leetcode-494. Target Sum
- Leetcode 494. Target Sum
- leetcode-494. Target Sum
- [LeetCode OJ]Target Sum
- 【Python爬虫5】提取JS动态网页数据
- yii2.0 rbac权限学习笔记 [ 2.0 版本 ]
- xampp 80 端口被占用解决方法
- jQuery如何设置下拉框显示与隐藏
- android app 社交动态
- leetcode[494]:Target Sum
- 【Python爬虫6】表单交互
- 开源路由软件Quagga安装及使用
- null!="" 常用的字符串非空判断
- 电商网站架构
- 我的Java设计模式学习笔记(2)- Bridge模式
- 今天第一天开通博客
- C#程序加壳
- Linux termios 串口编程之 VTIME与VMIN