topic description
problem solving ideas
Don't think about it, draw it, think of it as a tree, for traverses the width of the tree, and recursively traverses the depth of the tree
Code
class Solution {
private:
vector<int> path;//存放暂时结果
vector<vector<int>> result;//存放总结果
void backtracking(int n,int k,int startIndex){
//终止条件
if(path.size() == k){
result.push_back(path);
return;
}
for(int i = startIndex;i <= n;i++){
path.push_back(i);
backtracking(n, k, i + 1);//递归
path.pop_back();//就比如1 2 1 3 他们开头都是1,我们在把1 2加入到容器中之后 需要把2弹出才能得到1 3
}
}
public:
vector<vector<int>> combine(int n, int k) {
backtracking(n,k,1);
return result;
}
};