In C ++, the following procedure is specified:
template <typename Iterator> bool next_combination(const Iterator first, Iterator k, const Iterator last) { if ((first == last) || (first == k) || (last == k)) return false; Iterator i1 = first; Iterator i2 = last; ++i1; if (last == i1) return false; i1 = last; --i1; i1 = k; --i2; while (first != i1) { if (*--i1 < *i2) { Iterator j = k; while (!(*i1 < *j)) ++j; std::iter_swap(i1,j); ++i1; ++j; i2 = k; std::rotate(i1,j,last); while (last != j) { ++j; ++i2; } std::rotate(k,i2,last); return true; } } std::rotate(first,k,last); return false; }
Then you can do the following:
std::string s = "abcde"; for(std::size_t i = 1; i != s.size(); ++i) { do { std::cout << std::string(s.begin(),s.begin() + i) << std::endl; } while(next_combination(s.begin(),s.begin() + i,s.end())); }
Note. What would you expect to see combinations 2 ^ n-1, where n is the length of the array or string.
Matthieu N.
source share