当前位置:网站首页>Click: 377. Combined Sum Ⅳ
Click: 377. Combined Sum Ⅳ
2022-08-10 00:33: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]]
遍历顺序:
This is a complete backpack,So it's a sequential traversal,But the test cases given by this topic show thatdpThe sequences in are permutations,So pay attention to twoforThe order in which loops are nested
- 如果求组合数就是外层for循环遍历物品,内层for遍历背包
- 如果求排列数就是外层for遍历背包,内层for循环遍历物品
题目数据保证答案符合 32 位整数范围
- dp[j] < INT_MAX - dp[j - nums[i]]So there is this judgment condition
代码:
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];
}
};
边栏推荐
猜你喜欢
随机推荐
Mysql集群 ShardingSphere
torch.distributed多卡/多GPU/分布式DPP(二)——torch.distributed.all_reduce(reduce_mean)&barrier&控制进程执行顺序&随机数种子
What is the stability of the quantitative trading interface system?
JS中表单操作、addEventListener事件监听器
探索TiDB Lightning源码来解决发现的bug
HBuilder X 不能运行到内置终端
2022/8/9 考试总结
国内BI厂商一览
如何正则匹配乱码?
杭电多校-Counting Stickmen-(思维+组合数+容斥)
使用股票量化交易接口需要具备怎么样的心态
Leetcode 236. 二叉树的最近公共祖先
金仓数据库 KingbaseGIS 使用手册(6.3. 几何对象创建函数)
国内十大活跃报表 BI 产品深度对比及点评
xlrd 与 xlsxwritter 的基本操作
Analyses the development status quo of stock trading
力扣:322. 零钱兑换
全球不用交税的国家,为什么不交
HUAWEI CLOUD escorts the whole process of "Wandering Ark" for the first time, creating a popular brand
Qt message mechanism and events