当前位置:网站首页>力扣: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];
}
};
边栏推荐
- Interfering with BGP routing---community attributes
- Linux 配置MySQL
- mysql中的key是怎么用的,或者这个值有什么意义,如下图?
- xlrd 与 xlsxwritter 的基本操作
- 【Burning】It's time to show your true strength!Understand the technical highlights of the 2022 Huawei Developer Competition in one article
- What is the stability of the quantitative trading interface system?
- setter与getter访问器属性——数据驱动显示
- Redis集群
- 异常处理(try,catch,finally)
- 打包报错 AAPT: error: failed to read PNG signature: file does not start with PNG signature.
猜你喜欢
随机推荐
APS系统能消除造成生产和运输延迟的瓶颈
leetcode:331. 验证二叉树的前序序列化
web 面试高频考点 —— 性能优化篇(手写防抖、手写节流、XXS攻击、XSRF攻击)
Redis集群
three.js镂空圆球拖拽变形js特效
Good future, want to be a second new Oriental
linux上使用docker安装redis
迁移学习 & 凯明初始化
正则表达式的实际使用
【面试高频题】可逐步优化的链表高频题
Tencent continues to wield the "big knife" to reduce costs and increase efficiency, and free catering benefits for outsourced employees have been cut
kubesphere
安踏携手华为运动健康共同验证冠军跑鞋 创新引领中国体育
【对象——对象及原型链上的属性——对象的操作方法】
leetcode 20. Valid Parentheses 有效的括号(中等)
DXF笔记:文字对齐的研究
What are the basic steps to develop a quantitative trading strategy?
tiup cluster scale-out
VR全景拍摄如何拍摄?如何使用拍摄器材?
【Apifox】为什么如此受青睐,此篇文章和大家分享