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. TensorFlow(十一):递归神经网络(RNN与LSTM)

    RNN RNN(Recurrent Neural Networks,循环神经网络)不仅会学习当前时刻的信息,也会依赖之前的序列信息.由于其特殊的网络模型结构解决了信息保存的问题.所以RNN对处理时间序 ...

  2. Python的十种常见算法

    十种排序算法 1. 常见算法分类 十种常见排序算法一般分为以下几种: (1)非线性时间比较类排序: ​ a. 交换类排序(快速排序.冒泡排序) ​ b. 插入类排序(简单插入排序.希尔排序) ​ c. ...

  3. jmeter接口上传图片功能

    图片上传需要选择Files Upload 输入下列参数: File Path:方法一,把图片放在bin目录下,直接输入图片名称:方法二,点击下图“Browse”按钮,选择一张需要上传的图片,地址将会自 ...

  4. meshing-轴

    原视频下载地址:https://yunpan.cn/cqrJRm32dMmAL  访问密码 9dd9

  5. linux 关机/重启命令总结

    linux下常用的关机命令有:shutdown.halt.poweroff.init:重启命令有:reboot.下面本文就主要介绍一些常用的关机命令以及各种关机命令之间的区别和具体用法. 首先来看一下 ...

  6. 教你如何快速定制 SpringBoot banner

    之前说过如何快速创建SpringBoot项目,不知道的同学可以查看之前的文章 5分钟学会如何创建spring boot项目. 为了让大家脱单,码哥简直费尽心思,今天这个技能或许可以让你脱单! 今天我们 ...

  7. 2019 DDCTF 部分writeup

    网上的wp已经很多了,但wp普遍很简略.我尽量写的详细一点. 一.WEB 滴~ 拿到题目后首先右键查看源代码,发现图片是以base64传送的 而且看url发现里面应该是包含了文件名,并且用了某个编码. ...

  8. DOM 事件有哪些阶段?谈谈对事件代理的理解

    分为三大阶段:捕获阶段--目标阶段--冒泡阶段 事件代理简单说就是:事件不直接绑定到某元素上,而是绑定到该元素的父元素上,进行触发事件操作时(例如'click'),再通过条件判断,执行事件触发后的语句 ...

  9. 虎牙在全球 DNS 秒级生效上的实践 集群内通过 raft 协议同步数据,毫秒级别完成同步。

    https://mp.weixin.qq.com/s/9bEiE4QFBpukAfNOYhmusw 虎牙在全球 DNS 秒级生效上的实践 原创: 周健&李志鹏 阿里巴巴中间件 今天

  10. Ionic4.x 中的 UI 组件(UI Components) Slides 轮播图组件、Searchbar 组件、 Segment 组件

    Slides 轮播图组件 Ionic4.x 中的轮播图组件是基于 swiper 插件,所以配置 slides 的属性需要在 swiper 的 api 中 找 Swiper Api:http://ida ...