做組合
e.g. 從 4 取 2
path.size() == k
時才加入結果class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> ans;
vector<int> temp;
backtracking(ans, temp, n, k, 1);
return ans;
}
void backtracking(vector<vector<int>> &ans, vector<int> &temp, int n, int k, int start){
// 終止條件
if(temp.size()==k){
ans.push_back(temp);
return;
}
for(int i=start;i<n+1;i++){
temp.push_back(i);
backtracking(ans, temp, n, k, i+1);
temp.pop_back();
}
}
};