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

03.03回溯法

 

class Solution {
public:vector<int> temp;vector<vector<int>> ans;void dfs(int cur,int n,int k){//剪枝 temp 长度加上区间 [cur, n] 的长度小于 k,不可能构造出长度为 k 的 tempif(temp.size()+(n-cur+1)<k){return;}if(temp.size()==k){ans.push_back(temp);return;}temp.push_back(cur);dfs(cur+1,n,k);temp.pop_back();dfs(cur+1,n,k);}vector<vector<int>> combine(int n, int k) {dfs(1,n,k);   return ans;}
};
class Solution {
public:void dfs(vector<int>& candidates, int target, vector<vector<int>>& ans, vector<int>& combination, int idx){if(candidates.size()==idx){return;}if(target==0){ans.push_back(combination);return;}//直接跳过dfs(candidates,target,ans,combination,idx+1);//选择当前数if(target-candidates[idx]>=0){combination.emplace_back(candidates[idx]);//继续添加当前元素dfs(candidates,target-candidates[idx],ans,combination,idx);combination.pop_back();}}vector<vector<int>> combinationSum(vector<int>& candidates, int target) {vector< vector<int> >ans;vector<int> combination;dfs(candidates,target,ans,combination,0);return ans;}
};

 

http://www.lryc.cn/news/26833.html

相关文章:

  • I.MX6ULL内核开发0:linux内核模块
  • qsort快速排序的实现以及模拟实现qsort的功能(狠狠的拿捏)
  • [Java·算法·中等]LeetCode215. 数组中的第K个最大元素
  • xgboost:算法数学原理
  • map、multimap、unordered_map
  • 2023年全国最新会计专业技术资格精选真题及答案11
  • Centos7搭建NFS
  • ThreadLoca基本使用以及与synchronized的区别
  • 【C++】纯虚函数、纯虚析构
  • Python 进阶小技巧:7招展开嵌套列表
  • 【Spring6】| Bean的作用域
  • Qt界面美化之自定义qss样式表
  • 春招进行时:“211文科硕士吐槽工资5500” HR:行情和能力决定价值
  • 【DaVinci Developer专题】-45-自动生成SWC中所有Runnable对应的C文件
  • redis启动和关闭服务脚本
  • windows CMD快捷键:
  • 【C/C++语言】刷题|双指针|数组|单链表
  • Leetcode.1487 保证文件名唯一
  • python-星号(*)-双星号(**)-函数动态参数匹配-解包操作
  • 面试官:为什么说ArrayList线程不安全?
  • STP详解
  • linux AWK常用命令 —— 筑梦之路
  • SpringCloud:服务拆分及远程调用
  • 网络应用之javascript函数定义和调用
  • 使用VNC远程连接Ubuntu - 内网穿透实现公网远程办公
  • JavaScript Date 日期对象
  • 婴幼儿常见八大疾病及护理方法
  • UVa 817 According to Bartjens 数字表达式 DFS ID 迭代加深搜 逆波兰表达式
  • c++基础/类和对象
  • 2023年中国人工智能产业趋势报告