当前位置: 首页 > news >正文

leetcode刷题日记——1.组合总和

在这里插入图片描述
解答:

class Solution {
public:void dfs(vector<int>& candidates, int target, vector<vector<int>>& ans, vector<int>& combine, int idx) {if(idx==candidates.size()){//遍历完的边界return;}if(target==0){//找完了能组成和的所有数,也是边界ans.emplace_back(combine);//把单条结果放进去return;}dfs(candidates,target,ans,combine,idx+1);//如果我们不用当前idx数,要考虑下一个idx+1//如果要用当前idx数if(target-candidates[idx]>=0){//首先我们要确定还有空间可以用(数字全正啊,题目有说)combine.emplace_back(candidates[idx]);//还有空间,放进单条答案里dfs(candidates,target-candidates[idx],ans,combine,idx);//但是我们可以无限制的取当前数,所以可以继续考虑idxcombine.pop_back();//回溯的时候还原现场}}vector<vector<int>> combinationSum(vector<int>& candidates, int target) {vector<vector<int>> ans;//存答案用的vector<int> combine;//放单条答案用的dfs(candidates,target,ans,combine,0);//从0位置开始return ans;}
};

时间复杂度:O(S),S为所有可行解的长度之和。
空间复杂度:O(target)。除了答案数组外,空间复杂度取决于递归的栈深度,在最差情况下需要递归O(target)层。

相关文章:

  • 【论文解读】DeepSeek-R1
  • 常用存储器介绍
  • 操作系统:分页存储管理方式(精简版、含例题)
  • 无需登录即可使用的Web应用网站
  • MySQL事务与锁中的MVCC 深度解析与面试题讲解
  • C++学习-入门到精通【15】异常处理深入剖析
  • Docker安装MQEX
  • 20250607在荣品的PRO-RK3566开发板的Android13的uboot中使用gpio命令来配置GPIO的状态
  • VBA进度条ProgressForm1
  • 振动力学:多自由度系统
  • 现代C++特性(一):基本数据类型扩展
  • WaytoAGI东京大会开启AI全球化新对话:技术无国界,合作促创新
  • PCB设计教程【大师篇】——STM32开发板电源设计(电压基准、滤波电容)
  • PG 分区表的缺陷
  • 自制操作系统(五、重写引导部分和C语言的使用)
  • c++学习-this指针
  • 【仿生机器人】仿生机器人智能架构:从感知到个性的完整设计
  • 《Progressive Transformers for End-to-End Sign Language Production》复现报告
  • 【LangchainAgent】Agent基本构建与使用
  • 第七章 监听一致性协议 A Primer on Memory Consistency and Cache Coherence - 2nd Edition
  • cms网站建设有多少条数据/自己个人怎样做电商
  • wordpress邮件设置方法/厦门seo培训
  • wordpress photolux/河北优化seo
  • 合肥品牌网站建设/女孩短期技能培训班
  • 电子商务与网站建设/千锋教育学费多少
  • 外贸网站建设软件/百度北京总部电话