LeetCode(494):目标和 Target Sum(Java)

该博客介绍了如何解决LeetCode上的494题——目标和Target Sum,通过将问题转化为01背包问题,利用动态规划求解。博主分享了使用Java实现的解题思路,并提供了状态转移方程。
摘要由CSDN通过智能技术生成

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。现在你有两个符号 + 和 -。对于数组中的
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值