当前位置:网站首页>力扣:377. 组合总和 Ⅳ
力扣:377. 组合总和 Ⅳ
2022-08-09 22:11:00 【empty__barrel】
题目:
给你一个由 不同 整数组成的数组 nums ,和一个目标整数 target 。请你从 nums 中找出并返回总和为 target 的元素组合的个数。
题目数据保证答案符合 32 位整数范围。
解析:
dp数组含义:
dp[j]: 凑成目标正整数为i的排列个数为dp[i]
递推公式:
dp[i] += dp[i - nums[j]];
初始化:
初始化为0,这样才不会影响dp[i]累加所有的dp[i - nums[j]]
遍历顺序:
这是一个完全背包,所以是顺序遍历,但是这个题目给的测试用例表示dp中的序列是排列,所以要注意两个for循环嵌套的顺序
- 如果求组合数就是外层for循环遍历物品,内层for遍历背包
- 如果求排列数就是外层for遍历背包,内层for循环遍历物品
题目数据保证答案符合 32 位整数范围
- dp[j] < INT_MAX - dp[j - nums[i]]所以有这个判断条件
代码:
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<int>dp(target+1,0);
dp [0] = 1;
int bagweight = target;
for(int j = 0; j <= bagweight; ++j){
for(int i = 0; i < nums.size(); ++i){
if(j >= nums[i] && dp[j] < INT_MAX - dp[j - nums[i]]) dp[j] += dp[j-nums[i]];
}
}
return dp[target];
}
};
边栏推荐
- 联盟链技术应用的难点
- 高数_复习_第4章:向量代数和空间解析几何
- VR全景结合小程序,为线上电商更好的服务
- [WeChat applet development (8)] Summary of audio background music playback problems
- LeetCode_2632_字符串压缩
- Tencent continues to wield the "big knife" to reduce costs and increase efficiency, and free catering benefits for outsourced employees have been cut
- ArrayList 和 LinkedList 区别
- 用户要清晰知道,量化交易并非简单的程序
- charts.js插件实现的散点图样式
- VR全景拍摄如何拍摄?如何使用拍摄器材?
猜你喜欢
少儿编程 电子学会图形化编程等级考试Scratch三级真题解析(判断题)2022年6月
五分钟商学院(基础---商业篇)
Redis集群
Install win7 virtual machine in Vmware and related simple knowledge
Tencent continues to wield the "big knife" to reduce costs and increase efficiency, and free catering benefits for outsourced employees have been cut
中国SaaS企业排名,龙头企业Top10梳理
matplotlib散点图颜色分组图例
【Burning】It's time to show your true strength!Understand the technical highlights of the 2022 Huawei Developer Competition in one article
直播预告 | ICML 2022 11位一作学者在线分享神经网络,图学习等前沿研究
华为云全流程护航《流浪方舟》破竹首发,打造口碑爆款
随机推荐
异常处理(try,catch,finally)
HUAWEI CLOUD escorts the whole process of "Wandering Ark" for the first time, creating a popular brand
(转)字符集编码标识符,数字表示字符编码
DXF笔记:文字对齐的研究
生成NC文件时,报错“未定义机床”
如何坚持使用程序化系统?
leetcode:321. 拼接最大数
kubesphere
UNI-APP_监听页面滚动h5监听页面滚动
shader学习笔记(五)
用户要清晰知道,量化交易并非简单的程序
EasyExcel使用
Chapter 15 HMM模型
一体化伺服电机在三轴钻孔机中的应用
tiup cluster upgrade
leetcode:323. 无向图中连通分量的数目
Sun Zhengyi lost 150 billion: it was expensive at the beginning
【技术分享】SLA(服务等级协议)原理与配置
直播预告 | ICML 2022 11位一作学者在线分享神经网络,图学习等前沿研究
【Leetcode】2104. Sum of Subarray Ranges