fork(1) download
  1. #include <vector>
  2. using std::vector;
  3. #include <iostream>
  4. using std::cout;
  5.  
  6. //def powerSet(elts):
  7. vector<vector<int>> powerSet(const vector<int>& elts)
  8. {
  9. // if len(elts) == 0:
  10. if (elts.empty()) {
  11. // return [[]]
  12. return vector<vector<int>>(1, vector<int>());
  13. }
  14. // else:
  15. else {
  16. // smaller = powerSet(elts[1:])
  17. vector<vector<int>> allofthem = powerSet(
  18. vector<int>(elts.begin() +1, elts.end()));
  19. // elt = [elts[0]]
  20. int elt = elts[0]; // in Python elt is a list (of int)
  21. // withElt = []
  22. // for s in smaller:
  23. // withElt.append(s + elt)
  24. // allofthem = smaller + withElt
  25. const int n = allofthem.size();
  26. for (int i=0; i<n; ++i) {
  27. const vector<int>& s = allofthem[i];
  28. allofthem.push_back(s);
  29. allofthem.back().push_back(elt);
  30. }
  31. // return allofthem
  32. return allofthem;
  33. }
  34. }
  35.  
  36. int main()
  37. {
  38. const int N = 5;
  39. vector<int> input;
  40. for(int i=1; i<=N; ++i) {
  41. input.push_back(i);
  42. }
  43. vector<vector<int>> ps = powerSet(input);
  44. for(const vector<int>& set:ps) {
  45. cout << "[ ";
  46. for(int elt: set) {
  47. cout << elt << " ";
  48. }
  49. cout << "]\n";
  50. }
  51. return 0;
  52. }
  53.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
[ ]
[ 5 ]
[ 4 ]
[ 5 4 ]
[ 3 ]
[ 5 3 ]
[ 4 3 ]
[ 5 4 3 ]
[ 2 ]
[ 5 2 ]
[ 4 2 ]
[ 5 4 2 ]
[ 3 2 ]
[ 5 3 2 ]
[ 4 3 2 ]
[ 5 4 3 2 ]
[ 1 ]
[ 5 1 ]
[ 4 1 ]
[ 5 4 1 ]
[ 3 1 ]
[ 5 3 1 ]
[ 4 3 1 ]
[ 5 4 3 1 ]
[ 2 1 ]
[ 5 2 1 ]
[ 4 2 1 ]
[ 5 4 2 1 ]
[ 3 2 1 ]
[ 5 3 2 1 ]
[ 4 3 2 1 ]
[ 5 4 3 2 1 ]