当前位置:网站首页>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];
}
}
边栏推荐
猜你喜欢

判断JS数据类型的四种方法
![[Open class preview]: Research and application of super-resolution technology in the field of video quality enhancement](/img/fc/cd859efa69fa7b45f173de74c04858.png)
[Open class preview]: Research and application of super-resolution technology in the field of video quality enhancement

字体反爬之好租

程序员如何优雅地解决线上问题?

bpmn-process-designer基础上进行自定义样式(工具、元素、菜单)

Audio and Video Technology Development Weekly | 256

【公开课预告】:超分辨率技术在视频画质增强领域的研究与应用

Find objects with the same property value Cumulative number Summarize

Feign 从注册到调用原理分析

Process sibling data into tree data
随机推荐
程序员如何优雅地解决线上问题?
Aeraki Mesh 加入 CNCF 云原生全景图
How to use DevExpress controls to draw flowcharts?After reading this article, you will understand!
The difference between undefined and null in JS
Visualization of lag correlation of two time series data in R language: use the ccf function of the forecast package to draw the cross-correlation function, and analyze the lag correlation according t
SQL函数 %SQLUPPER
通讯录(静态版)(C语言)(VS)
SQL函数 %SQLSTRING
Data frame and remote frame of CAN communication
leetcode/子矩阵元素和
CAN通信的数据帧和远程帧
如何使用 Authing 单点登录,集成 Discourse 论坛?
R language ggplot2 visualization: use the ggdensity function of the ggpubr package to visualize density plots, use the stat_central_tendency function to add mean vertical lines to the density and cust
Qt获取文件夹下所有文件
MySQL调优
数据湖 delta lake和spark版本对应关系
字体反爬之好租
Ts-Map 类的使用
leetcode/submatrix element sum
动态库、静态库浅析