void dfs(vector<int> &num, vector<vector<int>> &res, vector<int> comb, int curr_len, int K, int begin, int n) {
if(curr_len == K) {
res.push_back(comb);
return;
}
for(int i=begin; i<n; i++) {
//swap(num[i], num[begin]); // no need to swap anymore, since we handle combination not permutation. order does not matter!
comb.push_back(num[i]);
dfs(num, res, comb, curr_len+1, K, i+1, n); // gist, should be i+1 not begin+1
comb.pop_back();
//swap(num[i], num[begin]);
}
}
vector<vector<int>> get_combinations(vector<int> &num, int K) {
vector<vector<int>> res;
vector<int> comb;
dfs(num, res, comb, 0, K, 0, num.size());
return res;
}
int main() {
vector<int> num = {1,2,3,4};
vector<vector<int>> res = get_combinations(num, 2);
for(auto a : res) {
for(int d : a) cout << d << " ";
cout << endl;
}
}