fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <numeric>
  4. #include <vector>
  5. #include <string>
  6.  
  7. std::string as_string(const std::vector<char>& vals, const std::vector<bool>& pattern)
  8. {
  9. std::string result;
  10.  
  11. for (unsigned i = 0; i < pattern.size(); ++i)
  12. if (pattern[i])
  13. result += vals[i];
  14.  
  15. return result;
  16. }
  17.  
  18. // Note: Only good for values greater than 0 and less than 10.
  19. std::vector<std::string> unique_combinations(unsigned val)
  20. {
  21. std::vector<std::string> result;
  22.  
  23. std::vector<char> vals(val);
  24. std::iota(vals.begin(), vals.end(), '1');
  25.  
  26. std::vector<bool> pattern(vals.size(), false);
  27.  
  28. for (auto it = pattern.rbegin(); it != pattern.rend(); ++it)
  29. {
  30. *it = true;
  31.  
  32. do
  33. {
  34. result.emplace_back(as_string(vals, pattern));
  35. } while (std::next_permutation(pattern.begin(), pattern.end()));
  36. }
  37.  
  38. return result;
  39. }
  40.  
  41. int main()
  42. {
  43. for (unsigned i = 1; i < 6; ++i)
  44. {
  45.  
  46. auto combos = unique_combinations(i);
  47.  
  48. // to present them in the same order as the sample
  49. auto ordering = [](const std::string& a, const std::string& b)
  50. {
  51. if (a.size() < b.size())
  52. return true;
  53.  
  54. if (a.size() > b.size())
  55. return false;
  56.  
  57. return a < b;
  58. };
  59.  
  60. std::sort(combos.begin(), combos.end(), ordering);
  61.  
  62. auto combo = combos.begin();
  63. while (combo != combos.end())
  64. {
  65. unsigned size = combo->size();
  66. std::cout << *combo;
  67.  
  68. while (++combo != combos.end() && combo->size() == size)
  69. std::cout << ", " << *combo;
  70.  
  71. std::cout << '\n';
  72. }
  73.  
  74. std::cout << '\n';
  75. }
  76. }
Success #stdin #stdout 0s 3436KB
stdin
Standard input is empty
stdout
1

1, 2
12

1, 2, 3
12, 13, 23
123

1, 2, 3, 4
12, 13, 14, 23, 24, 34
123, 124, 134, 234
1234

1, 2, 3, 4, 5
12, 13, 14, 15, 23, 24, 25, 34, 35, 45
123, 124, 125, 134, 135, 145, 234, 235, 245, 345
1234, 1235, 1245, 1345, 2345
12345