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. 【LOJ #3144】「APIO 2019」奇怪装置

    题意: 定义将一个\(t\)如下转换成一个二元组: \[ f(t) = \begin{cases} x = (t + \left\lfloor \frac{t}{B} \right \rfloor) ...

  2. 10月清北学堂培训 Day 5

    今天是廖俊豪老师的讲授~ T1 第一次想出正解 30 pts: k <= 10,枚举如何把数放到矩阵中,O ( k ! ): 100 pts: 对于矩阵的每一列,我们二分最小差异值,然后贪心去判 ...

  3. codeforces#1120C. Compress String(dp+后缀自动机)

    题目链接: https://codeforces.com/contest/1120/problem/C 题意: 从前往后压缩一段字符串 有两种操作: 1.对于单个字符,压缩它花费$a$ 2.对于末尾一 ...

  4. 【linux】保存屏幕日志log

    例如: #!/bin/bash #LOG="examples/mnist/lenet_log_mylog" LOG="LOG/log.txt.`date +'%Y-%m- ...

  5. Arts打卡第10周

    Algorithm.主要是为了编程训练和学习. 每周至少做一个 leetcode 的算法题(先从Easy开始,然后再Medium,最后才Hard). 进行编程训练,如果不训练你看再多的算法书,你依然不 ...

  6. 【hadoop环境问题】namenode无法启动问题解决

    [问题背景] 要在自己的阿里云上搭伪分布式,用来复习和强化hive相关的知识,在执行脚本 sh start-dfs.sh后,jps后: 然后查看name的日志,报错如下: [解决方法] 网上的很多方法 ...

  7. 20175313 张黎仙《获奖感想与Java阶段性学习总结》

    一.获奖感想 很荣幸能够成为为数不多的小黄衫获得者之一,这是对我近一学期以来学习成果的肯定,也激励着我更加努力学习. 首先我要感谢的人就是娄嘉鹏老师.我曾在师生关系中提到,我认为的好老师的特点之一是: ...

  8. RK3288 添加普通串口uart1和uart3

    CPU:RK3288 系统:Android 5.1 diff --git a/device/rockchip/common/init.connectivity.rc b/device/rockchip ...

  9. [ERR] 2006 - MySQL server has gone away如何解决

    解决方案: max_allowed_packet = 16M 改大点! 文章来源:外星人来地球 欢迎关注,有问题一起学习欢迎留言.评论

  10. [转][C#]Oracle 连接错误的解决

    错误1: .NET连接oracle,提示错误OCIEnvCreate 失败,返回代码为 -1,但错误消息文本不可用 两个原因: 1. 权限,把 Oracle 所在目录权限设置成 authenticat ...