fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <vector>
  4. using namespace std;
  5.  
  6. vector<vector<int>> fun(int pos, int n, int k, vector<int> &a) {
  7. if (pos == n || k == 0) {
  8. return {};
  9. }
  10. vector<vector<int>> ret;
  11. //include current element("pos") to the combinations
  12. auto v = fun(pos + 1, n, k - 1, a);
  13. for (auto c: v) {
  14. vector<int> cur = {a[pos]};
  15. //appends vector c to cur
  16. cur.insert(cur.end(), c.begin(), c.end());
  17. ret.push_back(cur);
  18. }
  19. if (k == 1) {
  20. ret.push_back({a[pos]});
  21. }
  22. //exclude current element("pos") from the combinations
  23. auto f = fun(pos + 1, n, k, a);
  24. //appends all vectors returned by f to the current result
  25. ret.insert(ret.end(), f.begin(), f.end());
  26. return ret;
  27. }
  28.  
  29. int main() {
  30. vector<int> a = {1, 2, 3, 4, 5};
  31. int n = a.size(), k = 3;
  32. auto res = fun(0, n, k, a);
  33. for (auto v: res) {
  34. for (auto x: v) {
  35. cout << x << " ";
  36. }
  37. cout << "\n";
  38. }
  39. cout << "Total number of " << k << "-combinations of " << n << "-elements set: " << res.size() << endl;
  40. return 0;
  41. }
Success #stdin #stdout 0.01s 5316KB
stdin
Standard input is empty
stdout
1 2 3 
1 2 4 
1 2 5 
1 3 4 
1 3 5 
1 4 5 
2 3 4 
2 3 5 
2 4 5 
3 4 5 
Total number of 3-combinations of 5-elements set: 10