mickypinata

LEET-T0077: Combinations

Dec 1st, 2021 (edited)
137
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<int> chosen;
  5.  
  6. void recur(vector<vector<int>> &ans, int n, int i, int k){
  7.     if(k == 0){
  8.         ans.push_back(chosen);
  9.         return;
  10.     }
  11.     for(; i <= n - k + 1; ++i){
  12.         chosen.push_back(i);
  13.         recur(ans, n, i + 1, k - 1);
  14.         chosen.pop_back();
  15.     }
  16. }
  17.  
  18. vector<vector<int>> combine(int n, int k){
  19.     vector<vector<int>> ans;
  20.     recur(ans, n, 1, k);
  21.     return ans;
  22. }
  23.  
  24. int main(){
  25.  
  26.     int n, k;
  27.     scanf("%d%d", &n, &k);
  28.     for(vector<int> &v : combine(n, k)){
  29.         cout << "[ ";
  30.         for(int x : v){
  31.             cout << x << ' ';
  32.         }
  33.         cout << "]\n";
  34.     }
  35.  
  36.     return 0;
  37. }
  38.  
RAW Paste Data Copied