Advertisement
jasonpogi1669

Generate All Possible Combinations and Permutations of a Sequence with Length of N using C++

Jan 21st, 2022
989
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.61 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. vector<vector<int>> res;
  6.  
  7. void Generate(vector<int>& vec, int n, int i = 0) {
  8.     if (i == n) {
  9.         res.push_back(vec);
  10.         return;
  11.     }
  12.     for (auto num : {0, 1, 2}) {
  13.         vec[i] = num;
  14.         Generate(vec, n, i + 1);
  15.     }
  16. }
  17.  
  18. int main() {
  19.     ios::sync_with_stdio(false);
  20.     cin.tie(0);
  21.     int n = 5;
  22.     vector<int> vec(n);
  23.     // generate sequence of length n using the given elements: {0, 1, 2}
  24.     Generate(vec, n);
  25.     for (int i = 0; i < (int) res.size(); i++) {
  26.         for (int j = 0; j < (int) res[i].size(); j++) {
  27.             cout << res[i][j] << " ";
  28.         }
  29.         cout << '\n';
  30.     }
  31.     return 0;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement