当前位置:网站首页>力扣:494. 目标和
力扣:494. 目标和
2022-08-07 07:35:00 【empty__barrel】
力扣:494. 目标和
题目:
给你一个整数数组 nums 和一个整数 target 。
向数组中的每个整数前添加 ‘+’ 或 ‘-’ ,然后串联起所有整数,可以构造一个 表达式 :
例如,nums = [2, 1] ,可以在 2 之前添加 ‘+’ ,在 1 之前添加 ‘-’ ,然后串联起来得到表达式 “+2-1” 。
返回可以通过上述方法构造的、运算结果等于 target 的不同 表达式 的数目。
解析:
0~n个物品放入容量为 j 的背包中其价值等于 j 的种类数 =
物品数为一个塞满背包的方法数
+物品数为两个塞满背包的方法数(且必须选定第二个物品才能是与之前不同的方法)
+物品数为三个塞满背包的方法数(且必须选定第三个物品才能是与之前不同的方法)
+物品数为n个塞满背包的方法数(其中必须选定第n个物品才能是与之前不同的方法)
此时可以看出dp[ j ]可以由前面的值表现出来,所以可以使用动态规划。
dp【j】的含义:
dp[j] 表示:填满j(包括j)这么大容积的包,有dp[j]种方法
dp数组的初始化:
dp[0] = 1,理论上也很好解释,装满容量为0的背包,有1种方法,就是装0件物品。
dp[j]其他下标对应的数值应该初始化为0,因为的物品数为0,那么装满容量为 j 的背包的方法数自然为0
确定递推公式:
由上述可知:dp[j] += dp[j - nums[i]]
确定遍历顺序:
第一个for遍历物品顺序遍历,第二个for遍历背包容量逆序遍历,其中背包容量需大于物品重量才执行循环体。
代码如下:
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
int sum = 0;
for (int i = 0; i < nums.size(); i++) sum += nums[i];
if (abs(S) > sum) return 0; // 此时没有方案
if ((S + sum) % 2 == 1) return 0; // 此时没有方案
int bagSize = (S + sum) / 2;
if (bagSize < 0) return 0;
vector<int> dp(bagSize + 1, 0);
dp[0] = 1;
for (int i = 0; i < nums.size(); i++) {
for (int j = bagSize; j >= nums[i]; j--) {
dp[j] += dp[j - nums[i]];
}
}
return dp[bagSize];
}
};
边栏推荐
- 模型微调迁移学习Finetune方法大全
- Model fine-tuning transfer learning Finetune method Daquan
- WEB安全基础 - - -弱口令和暴力破解
- Are there MCUs with 5nm process technology?
- PriorityQueue
- C学生数据库_读取文件中学生信息1。
- Related methods of getting the absolute path of the current file in the OS module
- 路由、 网络、互联网、因特网、公网私网IP、NAT技术
- Linux installation software command yum, apt-get
- A Pursuit of Temporal Accuracy in General Activity Detection TAG论文阅读笔记
猜你喜欢

Model fine-tuning transfer learning Finetune method Daquan

DeFi 前景展望:概览主流 DeFi 协议 Q2 进展

LeetCode 628. Maximum Product of Three Numbers

Graphical LeetCode - 1408. String Matching in Arrays (Difficulty: Easy)

Sort---Insertion sort

有 5nm 制程工艺的 MCU 吗?

Transport layer (UDP protocol, TCP protocol three-way handshake, four-way wave)

ASEMI整流桥GBL610参数,GBL610尺寸,GBL610特征

VoLTE Basic Self-Learning Series | What is Forking in SIP and IMS

ansible当中模块的使用
随机推荐
神经网络权值是什么意思,神经网络权重取值范围
一些零碎知识点的索引
【LeetCode】Day110-划分字母区间
WEB安全基础 - - -弱口令和暴力破解
2022A Special equipment related management (elevator) special work permit test question bank simulation test platform operation
黑马程序员会话Cookie&Session
【IO复用】select(处理读/写/异常事件)
VoLTE basic self-study series | IP layer routing and addressing process in IMS network (implementation in registration process)
信号工必备基础100问【转自微信公众号铁路信号技术交流】
10 years of experience summary: 7 tools for data analysts, focus on causal analysis!
LeetCode 1408. String matching in arrays
VoLTE Basic Self-Learning Series | What are transparent data and non-transparent data in VoLTE?
The use of modules in ansible
Redis 定长队列的探索和实践
2022 8.3 Simulation
QT不同子类间共享变量,教你简单、规范的方法
Web网页端IM产品RainbowChat-Web的v4.1版已发布
图解LeetCode——1408. 数组中的字符串匹配(难度:简单)
The second bullet of FPGA development: running water lamp experiment
JVM:(五)运行时数据区之虚拟机栈