当前位置:网站首页>LeetCode_494_目标和
LeetCode_494_目标和
2022-07-29 14:00:00 【Fitz1318】
题目链接
题目描述
给你一个整数数组 nums 和一个整数 target 。
向数组中的每个整数前添加 '+' 或 '-' ,然后串联起所有整数,可以构造一个 表达式 :
例如,nums = [2, 1] ,可以在 2 之前添加 '+' ,在 1 之前添加 '-' ,然后串联起来得到表达式 "+2-1" 。
返回可以通过上述方法构造的、运算结果等于 target 的不同 表达式 的数目。
示例 1:
输入:nums = [1,1,1,1,1], target = 3
输出:5
解释:一共有 5 种方法让最终目标和为 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
+1 + 1 + 1 + 1 - 1 = 3
示例 2:
输入:nums = [1], target = 1
输出:1
提示:
1 <= nums.length <= 200 <= nums[i] <= 10000 <= sum(nums[i]) <= 1000-1000 <= target <= 1000
解题思路
动态规划
- 将这些数分为两堆,+号为left,-号为right。然后相加和为
target,也就是left + right = target - 此外
left - right = sum,可以得到left = (sum + target) / 2 - 对于一个固定数组来说,
sum和target都是确定的,所以left可以求出来,此时问题就转换为在集合nums中找出和为left的组合,也就是装满容量为left的背包有几种方法
动态规划五部曲
- 确定
dp数组以及下标的含义dp[j]:装满j容量的背包,有dp[j]种方法
- 确定递推公式
- 在不考虑
nums[i]的情况下,装满容量为j - nums[i]的背包,有dp[j- nums[i]]种方法 - 因此
dp[j] += dp[j - nums[i]]
- 在不考虑
dp数组初始化dp[0] = 1,也就是装满容量为0的背包,有1种方法:就是装0个东西
- 确定遍历顺序
- 01背包问题种,
nums放在外循环,且是正序。target放在内循环,且为倒序
- 01背包问题种,
AC代码
class Solution {
public int findTargetSumWays(int[] nums, int target) {
int sum = 0;
for (int i : nums) {
sum += i;
}
if ((target + sum) % 2 != 0) {
return 0;
}
int bagWeight = (sum + target) / 2;
if (bagWeight < 0) {
bagWeight = -bagWeight;
}
int[] dp = new int[bagWeight + 1];
dp[0] = 1;
for (int i = 0; i < nums.length; i++) {
for (int j = bagWeight; j >= nums[i]; j--) {
dp[j] += dp[j - nums[i]];
}
}
return dp[bagWeight];
}
}
边栏推荐
猜你喜欢

kubernetes cks strace etcd

Network connection optimization for instant messaging mobile terminal development

Chinese Internet technology companies were besieged by wolves. Google finally suffered a severe setback and its profits fell sharply. It regretted promoting the development of Hongmeng...

在金融服务行业数字化转型中,低代码值得被关注
![[10:00 Open Class]: Application Exploration of Kuaishou GPU/FPGA/ASIC Heterogeneous Platform](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
[10:00 Open Class]: Application Exploration of Kuaishou GPU/FPGA/ASIC Heterogeneous Platform

The 10,000-character long article reveals the secrets of Huawei's data governance system!

EA&UML日拱一卒-活动图::Variable Actions(续)

如何返回一个数字的所有质因数?

Redis-NoSql

Understand the yolov7 network structure
随机推荐
PAT 甲级 A1021 Deepest Root
通过二维顺序表实现杨辉三角
你会看 MySQL 的执行计划(EXPLAIN)吗?
Violence recursion to dynamic programming 02 (very clever game of CARDS)
C#实现线程管理类
How to return all prime factors of a number?
国内helm快速安装和添加常用charts仓库
第4章_2——视图的使用
Bika LIMS 开源LIMS集—— SENAITE的使用(用户、角色、部门)
TCP和UDP的基本认识
2022开放原子全球开源峰会数据库分论坛圆满召开
【论文阅读】异常检测的视频通过Self-Supervised和多任务学习
The new technical director, who is in the form of a isXxx Boolean type definition, tomorrow need not come!
一文搞懂JS的原型链
PyQt5快速开发与实战 7.1 信号与槽介绍
进程间通信 --- system V三种通信方式(图文案例讲解)
教育部等五部门联合推荐优质课外资源,腾讯产品青少年模式首发
PAT serie a A1021 Deepest Root
84.(cesium之家)cesium模型在地形上运动
验证二叉树的前序序列化[抽象前序遍历]