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的更多相关文章

  1. [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 ...

  2. LeetCode Target Sum

    原题链接在这里:https://leetcode.com/problems/target-sum/description/ 题目: You are given a list of non-negati ...

  3. 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 ...

  4. Leetcode之深度优先搜索(DFS)专题-494. 目标和(Target Sum)

    Leetcode之深度优先搜索(DFS)专题-494. 目标和(Target Sum) 深度优先搜索的解题详细介绍,点击 给定一个非负整数数组,a1, a2, ..., an, 和一个目标数,S.现在 ...

  5. LC 494. Target Sum

    问题描述 You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 ...

  6. 59.Target Sum(目标和)

    Level:   Medium 题目描述: You are given a list of non-negative integers, a1, a2, ..., an, and a target, ...

  7. Longest subarray of target sum

    2018-07-08 13:24:31 一.525. Contiguous Array 问题描述: 问题求解: 我们都知道对于subarray的问题,暴力求解的时间复杂度为O(n ^ 2),问题规模已 ...

  8. [LeetCode] Target Sum 目标和

    You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symb ...

  9. [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 ...

  10. 494. Target Sum

    You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symb ...

随机推荐

  1. Python里面match()和search()的区别?

    答:re模块中match(pattern,string[,flags]),检查string的开头是否与pattern匹配. re模块中research(pattern,string[,flags]), ...

  2. ShardingSphere Hint模式 SpringBoot + Mybatis

    ShardingSphere Hint模式不需要对sql进行解析,就可以进行数据库或者表的路由.下面贴一下代码,关于SpringBoot + Mybatis + ShardingSphere怎样结合. ...

  3. FLUENT导入CHEMKIN机理的单位问题【转载】

    转载自:http://blog.sina.com.cn/s/blog_4a0a8b5d0101pj3c.html CHEMKIN机理导入后,发现速率常数全变了,那么他们是怎样变化的呢? FLUENT中 ...

  4. meshing-八分之一圆球

    ​原视频下载地址:https://yunpan.cn/cqwiFDCg6PbFj  访问密码 d1c8

  5. Ajax 是什么? 如何创建一个Ajax?

    ajax的全称:Asynchronous Javascript And XML. 异步传输+js+xml. 所谓异步,在这里简单地解释就是:向服务器发送请求的时候,我们不必等待结果,而是可以同时做其他 ...

  6. 三种Timer使用

    System.Windows.Forms.Timer,  System.Threading.Timer,  System.Timer,三种Timer使用如下 第一种:System.Windows.Fo ...

  7. php - ftp 上传文件到远程服务器

    ccentos7服务器 ======================== 一.安装vsftpd及ftp命令 yum install vsftpd -y yum install ftp -y 二.vsf ...

  8. AndroidStudio导入开源项目提示报错:Gradle sync failed: SSL peer shut down incorrectly

    问题描述: AndroidStudio导入开源项目提示报错:Gradle sync failed: SSL peer shut down incorrectly (1 m 12 s 92 ms) 解决 ...

  9. SpringBoot+Mybatis+Maven+MySql小案例

    数据准备: 建表t_user ,插入数据..... 创建工程 构建pom.xml <?xml version="1.0" encoding="UTF-8" ...

  10. Tracker 服务器地址大全 Tracker List

    https://dns.icoa.cn/tracker/ udp://tracker.tiny-vps.com:6969/announce https://1337.abcvg.info/announ ...