当前位置:网站首页>LeetCode_动态规划_中等_377.组合总和 Ⅳ
LeetCode_动态规划_中等_377.组合总和 Ⅳ
2022-08-01 12:21:00 【小城老街】
1.题目
给你一个由不同整数组成的数组 nums ,和一个目标整数 target 。请你从 nums 中找出并返回总和为 target 的元素组合的个数。
题目数据保证答案符合 32 位整数范围。
示例 1:
输入:nums = [1,2,3], target = 4
输出:7
解释:
所有可能的组合为:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
请注意,顺序不同的序列被视作不同的组合。
示例 2:
输入:nums = [9], target = 3
输出:0
提示:
1 <= nums.length <= 200
1 <= nums[i] <= 1000
nums 中的所有元素互不相同
1 <= target <= 1000
进阶:如果给定的数组中含有负数会发生什么?问题会产生何种变化?如果允许负数出现,需要向题目中添加哪些限制条件?
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/combination-sum-iv
2.思路
(1)动态规划
本题可以看作70.爬楼梯这题的升级版:
① 将 target 看作楼梯总台阶数;
② 数组 nums 中的元素是每次上楼梯时可爬的台阶数,例如 nums = [1,2,3] 表示每次上楼梯可以选择爬 1 或 2 或 3 个台阶;
③ 最终到达楼顶所爬的台阶数应该正好等于 target;
④ 现在要计算有多少种不同的方法可以爬到楼顶。
先定义 dp 数组,令 dp[i] 表示爬到第 i 阶楼梯的方法数,其中 1 ≤ i ≤ target。那么按照70.爬楼梯这题中的思路可以推出本题的状态转移方程为
dp[i] = dp[i] + dp[i - num],其中 num 是数组 nums 中所有小于等于 i 的元素。
相似题目:
LeetCode_回溯_中等_39.组合总和
LeetCode_回溯_中等_40.组合总和 II
LeetCode_回溯_中等_216.组合总和 III
3.代码实现(Java)
//思路1————动态规划
class Solution {
public int combinationSum4(int[] nums, int target) {
// dp[i] 表示从 nums 中找出并返回总和为 i 的元素组合的个数
int[] dp = new int[target + 1];
// 初始化
dp[0] = 1;
for (int i = 1; i <= target; i++) {
for (int num : nums) {
if (num <= i) {
dp[i] += dp[i - num];
}
}
}
return dp[target];
}
}
边栏推荐
- 迁移学习冻结网络的方法:
- CloudCompare & PCL ICP registration (point to face)
- Data frame and remote frame of CAN communication
- Aeraki Mesh Joins CNCF Cloud Native Panorama
- Aeraki Mesh 正式成为 CNCF 沙箱项目
- 2022 Go ecosystem rpc framework Benchmark
- CAN通信的数据帧和远程帧
- How to integrate 3rd party service center registration into Istio?
- Excel表格打印时不打印标记填充颜色
- What is MNIST (what does plist mean)
猜你喜欢
随机推荐
Js手写函数之new的模拟实现
判断JS数据类型的四种方法
SCHEMA solves the puzzle
Alibaba Cloud Official Redis Development Specification
Audio and Video Technology Development Weekly | 256
浏览器存储
MVVM响应式
2022 Go ecosystem rpc framework Benchmark
Grafana 9.0 released, Prometheus and Loki query builders, new navigation, heatmap panels and more!
如何成功通过 CKA 考试?
Process sibling data into tree data
ddl and dml in sql (the difference between database table and view)
【Unity3D插件】AVPro Video插件分享《视频播放插件》
SQL函数 SQRT
This article will take you to thoroughly clarify the working mechanism of certificates in Isito
【讲座分享】“营收“看金融
CloudCompare & PCL ICP registration (point to face)
如何利用DevExpress控件绘制流程图?看完这篇文章就懂了!
【社区明星评选】第24期 8月更文计划 | 笔耕不辍,拒绝躺平!更多原创激励大礼包,还有华为WATCH FIT手表!
Simulation implementation of new of Js handwritten function








