力扣 题目77- 组合
题目
题解
回溯算法+递归 这题属于很典型的回溯算法题了 都做到77了应该没什么要说的了 懂得都懂
代码
1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 int loop(int &n,int &k, vector<vector<int>> &result, vector<int> &alone,int begin,int end) { 5 if (alone.size() == k) { 6 result.push_back(alone); 7 return 0; 8 } 9 for (int i = begin; i <= end; i++) { 10 alone.push_back(i); 11 loop(n, k, result, alone, i+1, end+1); 12 alone.pop_back(); 13 } 14 return 0; 15 } 16 class Solution { 17 public: 18 vector<vector<int>> combine(int n, int k) { 19 vector<vector<int>> result; 20 vector<int> alone; 21 loop(n,k, result, alone,1,n-k+1); 22 return result; 23 } 24 }; 25 26 int main() { 27 Solution sol; 28 int n = 3; 29 int k = 2; 30 vector<vector<int>> result=sol.combine(n,k); 31 for (int i = 0; i < result.size(); i++) { 32 for (int j = 0; j < k; j++) { 33 cout << result[i][j] << " "; 34 } 35 cout << endl; 36 } 37 }