Ghytro

combinations.cpp

Feb 18th, 2021
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. template <typename T>
  2. std::vector<std::vector<T>> combinations(const std::vector<T> &vector,
  3.                                          const size_t &combinations_len)
  4. {
  5.     std::function<
  6.         void(const std::vector<T>&,
  7.              const size_t&,
  8.              std::vector<std::vector<T>>&,
  9.              std::vector<T>&,
  10.              size_t)
  11.     > __combinations;
  12.     __combinations = [&__combinations]
  13.     (const std::vector<T> &v,
  14.      const size_t &len,
  15.      std::vector<std::vector<T>> &ans,
  16.      std::vector<T> &comb,
  17.      size_t current_index)
  18.     {
  19.         if (comb.size() == len)
  20.         {
  21.             ans.push_back(comb);
  22.             return;
  23.         }
  24.  
  25.         for (size_t i = current_index + 1; i < v.size(); ++i)
  26.         {
  27.             comb.push_back(v[i]);
  28.             __combinations(v, len, ans, comb, i);
  29.             comb.pop_back();
  30.         }
  31.     };
  32.  
  33.     std::vector<std::vector<T>> ans;
  34.     std::vector<T> comb;
  35.     __combinations(vector, combinations_len, ans, comb, -1);
  36.     return ans;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment