当前位置:网站首页>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];
}
};
边栏推荐
猜你喜欢
随机推荐
Bi Sheng Compiler Optimization: Lazy Code Motion
VR全景结合小程序,为线上电商更好的服务
H5实现分享功能
Redis集群
Click: 518. Change Exchange II
Gartner全球集成系统市场数据追踪,超融合市场增速第一
Comprehensive analysis of FPGA basics
全面解析FPGA基础知识
Chapter 15 HMM模型
torch.distributed多卡/多GPU/分布式DPP(二)——torch.distributed.all_reduce(reduce_mean)&barrier&控制进程执行顺序&随机数种子
高数_复习_第4章:向量代数和空间解析几何
What are the basic steps to develop a quantitative trading strategy?
技术盛宴!华云数据携六大议题亮相OpenInfra Days China
【面试高频题】可逐步优化的链表高频题
中国SaaS企业排名,龙头企业Top10梳理
【燃】是时候展现真正的实力了!一文看懂2022华为开发者大赛技术亮点
Janus官方DEMO介绍
shell array
JS--hashchange事件--使用/教程
安踏携手华为运动健康共同验证冠军跑鞋 创新引领中国体育