fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <functional>
  4.  
  5. using namespace std;
  6.  
  7. bool nextSubsetIndex(std::vector<int> &a, int n) {
  8. for (int i = a.size() - 1; i >=0; --i) {
  9. n--;
  10. if (a[i] < n) {
  11. int x = ++a[i];
  12. for (int j = i + 1; j < a.size(); ++j) {
  13. a[j] = ++x;
  14. }
  15. return true;
  16. }
  17. }
  18.  
  19. return false;
  20. }
  21.  
  22. void generateSubset(int n, int k, std::function<void(const std::vector<int> &)> f) {
  23. std::vector<int> a(k);
  24.  
  25. for (size_t i=0; i<k; ++i) {
  26. a[i] = i;
  27. }
  28.  
  29. do {
  30. f(a);
  31. } while (nextSubsetIndex(a, n));
  32. }
  33.  
  34. int main() {
  35. int n, k;
  36.  
  37. while (std::cin >> n >> k) {
  38. generateSubset(n, k, [](auto a) {
  39. for (auto x : a) {
  40. std::cout << x + 1 << ", ";
  41. }
  42. std::cout << '\n';
  43. });
  44. std::cout << "------\n";
  45. }
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0s 4460KB
stdin
5 2
5 3
stdout
1, 2, 
1, 3, 
1, 4, 
1, 5, 
2, 3, 
2, 4, 
2, 5, 
3, 4, 
3, 5, 
4, 5, 
------
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, 
------