当前位置:网站首页>头脑风暴:目标和
头脑风暴:目标和
2022-08-10 14:51:00 【InfoQ】
题目
输入:nums: [1, 1, 1, 1, 1], S: 3
输出:5
- 数组非空,且长度不会超过 20 。
- 初始的数组的和不会超过 1000 。
- 保证返回的最终结果能被 32 位整数存下。
解题思路
代码实现
class Solution {
public int findTargetSumWays(int[] nums, int target) {
int sum = 0;
for (int i = 0; i < nums.length; i++) sum += nums[i];
if ((target + sum) % 2 != 0) return 0;
int size = (target + sum) / 2;
if(size < 0) size = -size;
int[] dp = new int[size + 1];
dp[0] = 1;
for (int i = 0; i < nums.length; i++) {
for (int j = size; j >= nums[i]; j--) {
dp[j] += dp[j - nums[i]];
}
}
return dp[size];
}
}
最后
- 时间复杂度:O(n × m),n为正数个数,m为背包容量
- 空间复杂度:O(m),m为背包容量
边栏推荐
猜你喜欢
PyTorch multi-machine multi-card training: DDP combat and skills
Oracle数据库备份dmp文件太大,有什么办法可以在备份的时候拆分成多个dmp吗?
数据在内存中的存储
字节终面:CPU 是如何读写内存的?
PyTorch 多机多卡训练:DDP 实战与技巧
NFT数字藏品——数字藏品发行平台开发
物资采购小程序开发制作功能介绍
【有限元分析】异型密封圈计算泄漏量与参数化优化过程(带分析源文件)
【MindSpore易点通机器人-02】设计与技术选型
Unfinished mathematics test paper ----- test paper generator (Qt includes source code)
随机推荐
宝塔面板开放Redis给指定外网机器
PAT甲级 1014 排队等候(队列大模拟+格式化时间)
@RequestBody的使用[通俗易懂]
物资采购小程序开发制作功能介绍
Mini Program-Voice broadcast function
网络工程师的背包(EDC总结推荐)
Zhaoqi Technology Innovation High-level Talent Entrepreneurship Competition Platform
How to code like a pro in 2022 and avoid If-Else
BCG库简介
小程序-语音播报功能
Summary of tensorflow installation stepping on the pit
1004 (tree array + offline operation + discretization)
DB2查询2个时间段之间的所有月份,DB2查询2个时间段之间的所有日期
Redis -- Nosql
领域驱动模型设计与微服务架构落地-从项目去剖析领域驱动
解读STEAM教育中的表现性评价
微信扫码登陆(1)—扫码登录流程讲解、获取授权登陆二维码
SWIG tutorial "two"
[Semantic Segmentation] DeepLab Series
Flask框架——MongoEngine使用MongoDB数据库