首页 > 其他分享 >代码随想录day24

代码随想录day24

时间:2022-10-25 10:48:56浏览次数:74  
标签:int day24 代码 随想录 startIndex vector result path backtracking

77. 组合

解题步骤:

 

 1、确定回溯函数参数及返回值;

        vector<vector<int>> result;         vector<int> path;         void backtracking (int n, int k, int startIndex) 2、确定回溯结束条件   单层路径大小为k             if (path.size() == k) {                 result.push_back(path);                 return;             } 3、确定单层逻辑             for (int i = startIndex; i <= n; i++) {                 path.push_back(i);//处理节点                 backtracking(n, k, i + 1);//递归                 path.pop_back();//回溯             } 代码如下:
 1 class Solution {
 2 private:
 3         vector<vector<int>> result;
 4         vector<int> path;
 5         void backtracking (int n, int k, int startIndex) {
 6             if (path.size() == k) {
 7                 result.push_back(path);
 8                 return;
 9             }
10             for (int i = startIndex; i <= n; i++) {
11                 path.push_back(i);
12                 backtracking(n, k, i + 1);
13                 path.pop_back();
14             }
15         }
16 public:
17     vector<vector<int>> combine(int n, int k) {
18         result.clear();
19         path.clear();
20         backtracking(n, k , 1);
21         return result;
22     }
23 };
       

标签:int,day24,代码,随想录,startIndex,vector,result,path,backtracking
From: https://www.cnblogs.com/zsqy/p/16824048.html

相关文章