2019.10.24 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)
github:https://github.com/ChopinXBP/LeetCode-Babel
这题表面上是一道递归问题,好在递归层数也不是特别多,每层分支也不是很爆炸,所以直接递归也不会超时。不过这题有个更巧妙的方法,能够转换成一个01背包问题。
将数据N看成AB两个部分,A符号全取正,B符号全取负,有
sumA - sumB = S
等式变换有
2 * sumA = S + sumA + sumB = S + sumN = target (令target = S + sumN)
因此只要在数组里找到一个集合A满足
sumA = target / 2
即为一个可行解。问题转换为01背包问题:
创建动态规划数组dp,dp[i]代表构成和为i的集合的数量,空集存在因此dp[0] = 1。状态转移方程为:
dp[i] += dp[i - num]; (i >= num)
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.
给定一个非负整数数组,a1, a2, …, an, 和一个目标数,S。现在你有两个符号 + 和 -。对于数组中的任意一个整数,你都可以从 + 或 -中选择一个符号添加在前面。
返回可以使最终数组和为目标数 S 的所有添加符号的方法数。
示例 1:
输入: nums: [1, 1, 1, 1, 1], S: 3
输出: 5
解释:
-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
一共有5种方法让最终目标和为3。
注意:
数组非空,且长度不会超过20。
初始的数组的和不会超过1000。
保证返回的最终结果能被32位整数存下。
/**
*
* 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.
* 给定一个非负整数数组,a1, a2, ..., an, 和一个目标数,S。现在你有两个符号 + 和 -。对于数组中的