I enter for example the set 1 2 3 4

Should bring like

 2 3 4, 1 3 4, 1 2 4, 1 2 3, 1 2, 1 3, 1 4, 2 3, 2 4, 3 4, 1, 2, 3, 4 

So far, it turns out normally to withdraw

 2 3 4, 1 3 4, 1 2 4, 1 2 3 

What to change / add to display the remaining subsets? And I need a job with recursion.

 #include <iostream> using namespace std; int rec(int *mas, int n); int n, m, null; int main () { cout << "n = "; cin >> n; cout << "Array: "; m = n; null = 0; int* mas = new int[n]; for (int i = 0; i < n; i++) { cin >> mas[i]; } rec(mas, n); system("pause"); return 0; } int rec(int *mas, int n) { for (int i = 0; i < n; i++) { if (i != null) { cout << mas[i] << " "; } } cout << endl; null++; m--; if (m == 0) { return 0; } else rec(mas, n); return 0; } 
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

Here so will arrange?

 #include <vector> #include <string> #include <iostream> #include <iomanip> using namespace std; vector<int> arr = { 1, 2, 3, 4 }; void outMas(const vector<int>&mas, int num, string s) { if (num == mas.size()) { cout << s << '\n'; return; } outMas(mas,num+1,s); s = s + to_string(mas[num]) + ' '; outMas(mas,num+1,s); } int main() { outMas(arr,0,""); } 

Those. Each call works with the element num - it either does not exist or it exists. Accordingly, we call on by passing the string either without this element or with it ...

  • But how does this work? - NiggaR
  • Recursively :) Roughly speaking, if we know how to derive all the subsets of N-1 elements, then to get for a set of N elements, for each one we can simply add or nothing (the Nth element is not included in the subset), or this Nth element. outMas (mas, num, s) adds to the string s in turn all the subsets of mas elements, starting with num. When all elements are enumerated (num is equal to the length of mas), the corresponding line is output. So clearer? PS If the answer suits you - mark it as accepted (the daw in front of the answer) ... - Harry