代码随想录算法训练营第二十一天| 77. 组合
回溯——组合
思路:
套了K次的循环,如何对K次循环呢,就需要一个startIndex,用它来控制从哪里开始
代码:
1 void combine_backTrack(int n, int k, int startIndex, vector<int>& path, vector<vector<int>>& result) 2 { 3 //中止条件 4 if (path.size() == k) 5 { 6 result.push_back(path); 7 return; 8 } 9 10 for (int i = startIndex; i <= n; i++) 11 { 12 path.push_back(i); 13 combine_backTrack(n, k, i + 1, path, result); 14 path.pop_back(); 15 } 16 } 17 18 vector<vector<int>> combine(int n, int k) { 19 vector<vector<int>> result; 20 if (n == 0) return result; 21 vector<int> path; 22 combine_backTrack(n, k, 1, path, result); 23 return result; 24 }
剪枝操作:
需要n-(k-p.size())+1
代码:
1 void combine_backTrack(int n, int k, int startIndex, vector<int>& path, vector<vector<int>>& result) 2 { 3 //中止条件 4 if (path.size() == k) 5 { 6 result.push_back(path); 7 return; 8 } 9 10 for (int i = startIndex; i <= (n-(k-path.size())+1); i++) 11 { 12 path.push_back(i); 13 combine_backTrack(n, k, i + 1, path, result); 14 path.pop_back(); 15 } 16 } 17 18 vector<vector<int>> combine(int n, int k) { 19 vector<vector<int>> result; 20 if (n == 0) return result; 21 vector<int> path; 22 combine_backTrack(n, k, 1, path, result); 23 return result; 24 }