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.
因为这里涉及到多种不同的选择,所以很容易联想到用dfs,代码如下:
class Solution {
public int findTargetSumWays(int[] nums, int S) {
int[] count = { };
helper(nums, , S, count);
return count[];
}
private void helper(int[] nums, int index, int S, int[] count) {
if (index == nums.length && S == ) {
count[]++;
}
if (index >= nums.length) return;
helper(nums, index + , S + nums[index], count);
helper(nums, index + , S - nums[index], count);
}
}
但是这种方法明显是没有优化的,所以时间比其他方法要高。简单的优化就是当我们到了i-th这个位置的时候,如果发现后面部分的值的和或者差都不可能达到target值,我们就应该放弃。
public class Solution {
public int findTargetSumWays(int[] nums, int S) {
if(nums == null || nums.length == ) return ;
int n = nums.length;
int[] sums = new int[n];
int[] count = { };
sums[n - ] = nums[n - ];
for (int i = n - ; i >= ; i--) {
sums[i] = sums[i + ] + nums[i];
}
helper(nums, sums, S, , count);
return count[];
}
public void helper(int[] nums, int[] sums, int target, int pos, int[] count){
if(pos == nums.length && target == ){
count[]++;
}
if (pos == nums.length) return;
if (sums[pos] < Math.abs(target)) return;
helper(nums, sums, target + nums[pos], pos + , count);
helper(nums, sums, target - nums[pos], pos + , count);
}
}
还有就是通过dp来做,解法如下:https://leetcode.com/problems/target-sum/discuss/97335/Short-Java-DP-Solution-with-Explanation
this is a classic knapsack problem
in knapsack, we decide whether we choose this element or not
in this question, we decide whether we add this element or minus it
So start with a two dimensional array dp[i][j] which means the number of ways for first i-th element to reach a sum j
we can easily observe that dp[i][j] = dp[i-1][j+nums[i]] + dp[i-1][j-nums[i],
Another part which is quite confusing is return value, here we return dp[sum+S], why is that?
because dp's range starts from -sum --> 0 --> +sum
so we need to add sum first, then the total starts from 0, then we add S
Actually most of Sum problems can be treated as knapsack problem, hope it helps
public int findTargetSumWays(int[] nums, int S) {
int sum = ;
for(int n: nums){
sum += n;
}
if (S < -sum || S > sum) { return ;}
int[][] dp = new int[nums.length + ][ * sum + ];
dp[][ + sum] = ; // 0 + sum means 0, 0 means -sum, check below graph
for(int i = ; i <= nums.length; i++){
for(int j = ; j < * sum + ; j++){
if(j + nums[i - ] < * sum + ) dp[i][j] += dp[i - ][j + nums[i - ]];
if(j - nums[i - ] >= ) dp[i][j] += dp[i - ][j - nums[i - ]];
}
}
return dp[nums.length][sum + S];
}
Target Sum的更多相关文章
- [Leetcode] DP -- Target Sum
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symb ...
- LeetCode Target Sum
原题链接在这里:https://leetcode.com/problems/target-sum/description/ 题目: You are given a list of non-negati ...
- LN : leetcode 494 Target Sum
lc 494 Target Sum 494 Target Sum You are given a list of non-negative integers, a1, a2, ..., an, and ...
- Leetcode之深度优先搜索(DFS)专题-494. 目标和(Target Sum)
Leetcode之深度优先搜索(DFS)专题-494. 目标和(Target Sum) 深度优先搜索的解题详细介绍,点击 给定一个非负整数数组,a1, a2, ..., an, 和一个目标数,S.现在 ...
- LC 494. Target Sum
问题描述 You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 ...
- 59.Target Sum(目标和)
Level: Medium 题目描述: You are given a list of non-negative integers, a1, a2, ..., an, and a target, ...
- Longest subarray of target sum
2018-07-08 13:24:31 一.525. Contiguous Array 问题描述: 问题求解: 我们都知道对于subarray的问题,暴力求解的时间复杂度为O(n ^ 2),问题规模已 ...
- [LeetCode] Target Sum 目标和
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symb ...
- [Swift]LeetCode494. 目标和 | Target Sum
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symb ...
- 494. Target Sum
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symb ...
随机推荐
- Python Tinker学习笔记
一直在简单看看python,这次项目需要做个界面,最好是要跨平台的,之前考虑QT,但是树莓派上QT跨平台编译一直装这有问题,后来发现Python不就可以么? 于是决定用python做个界面,但是做界面 ...
- ROSservice 通信方式
操作演示,对 service 通信的理解请看:点击打开链接 1. 使用 rosservice 1.1 rosservice list 假设小乌龟节点仍在运行 rosrun turtlesim tu ...
- WPF中打开网页的两种方法
1.浏览器打开 Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = "http://www. ...
- rethinkDB python入门
Start the server For a more detailed look, make sure to read the quickstart. $ rethinkdb Import the ...
- 运维管理SLA
主要三个概念: SLI 服务关键量化指标,即测试哪些指标,如何测等 SLO :服务等级目标,即要达到哪些目标,如设备正常率3个9.4个9等,即99.9% SLA: 服务等级协议,即如果未完成SLO中 ...
- 小福bbs——项目需求分析
# 一.简单了解 这个作业属于哪个课程 班级链接 这个作业要求在哪里 作业要求的链接 团队名称 小福bbs 这个作业的目标 第一个版本,根据项目预期情况形成 作业的正文 小福bbs--项目需求分析 其 ...
- mysql 实现同一个sql查询 分页数据 和总记录数
$get_sql = "SELECT sql_calc_found_rows field1,field2 FROM table WHERE name = '1' order by add_t ...
- 【Oracle/Maven】Maven导入oracle11g 自携带jdbc驱动包ojdbc6.jar到本地库
Maven需要下载解压并添加到classpath,如果不明可以参考https://www.cnblogs.com/xiandedanteng/p/11403480.html 然后在命令行窗口执行: m ...
- 【Python】把文件名命名成canlendar.py竟然导致无法使用canlendar模块 附赠2020年月历
这个bug困扰了我一阵,直到在 http://www.codingke.com/question/15489 找到了解决问题的钥匙,真是没想到居然是这个原因导致的. 下面是出错信息,可以看到只要目录下 ...
- 超详细Qt5.9.5移植攻略
本文就来介绍下如何将Qt5.9.5移植到ARM开发板上. 以imx6开发板为例,使用Ubuntu14.04虚拟机作为移植环境. 准备工作 1.主机环境:Ubuntu14.04: 开发板:启扬IAC-I ...