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 ...
随机推荐
- bzoj 3398
f[i]表示最后一个是公牛的方案数,=sigma(f[j])(j<i-k) 然后前缀和优化即可. #include <cstdio> #include <cstdlib> ...
- Our Journey of Dalian Ends && Our Journey of Xian Ends 最小费用最大流
2017 ACM-ICPC 亚洲区(乌鲁木齐赛区)网络赛Our Journey of Dalian Ends 题意:要求先从大连到上海,再从上海打西安,中途会经过其他城市,每个城市只能去一次,出一次, ...
- GO 跟C++/C差异
规范的语法(不需要符号表来解析) 垃圾回收(独有) 无头文件 明确的依赖 无循环依赖 常量只能是数字 int和int32是两种类型 字母大小写设置可见性(letter case sets visibi ...
- nessus在Linux上的安装
Nessus有三种安装方式 1.源文件安装 源文件安装是最复杂的安装方式,用此方式安装可以修改配置参数. 2.rpm安装 rpm安装比起源文件安装更简单一些,它已经把一些底层的东西写好了,用户只要按步 ...
- Java 面向对象(十三)
异常 什么是异常 异常 :指的是程序在执行过程中,出现的非正常的情况,最终会导致JVM的非正常停止. 在Java等面向对象的编程语言中,异常本身是一个类,产生异常就是创建异常对象并抛出了一个异常对象. ...
- Cesium中的坐标系及转换
在我们开始学习Entity之前,我们首先需要先学习下Cesium中的坐标系,Cesium中有多个坐标系,在进行添加Entity时经常会使用到. 一.坐标系介绍 我们先来列举下Cesium中的坐标系:W ...
- 阿里云服务器配置https(总结)
阿里云服务器配置https(总结) 一.总结 一句话总结: 1.下载https证书(可以在阿里云上) 2.在服务器上面开启443端口 3.配置apache服务器,443的加ssl,让80的重定向到44 ...
- arcgis python 一个mxd打包mpk
def onempk(fileName): if fileName: mxd = arcpy.mapping.MapDocument(fileName) else: mxd = arcpy.mappi ...
- 腾讯基于 Flink 的实时流计算平台演进之路
https://mp.weixin.qq.com/s/MGnG_Mpf6CUQWLJHvmWqLA
- delphi 获得父目录–指定级父目录
function get_dir_parent(dir:string;n:integer):string; //n为几级父目录varst:string;i:integer;begin st:=GetC ...