30 Day Challenge Day 14 | Leetcode 77. Combinations
题解
Medium | Backtracking
经典的排列组合题,使用回溯法。必须熟练。
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> combinations;
vector<int> combination;
helper(n, k, 1, combination, combinations);
return combinations;
}
void helper(int n, int k, int pos, vector<int>& combination, vector<vector<int>>& combinations) {
if(k == 0) {
combinations.push_back(combination);
return;
}
for(int i = pos; i <= n; i++) {
combination.push_back(i);
helper(n, k-1, i+1, combination, combinations);
combination.pop_back();
}
}
};