combinations algorithm

后端 未结 3 1233
攒了一身酷
攒了一身酷 2020-12-06 14:00

I want to make simple sorting algorithm.

given the input \"abcde\", I would like the output below. could you tell me the algorithm for that?

arr[0] =         


        
3条回答
  •  半阙折子戏
    2020-12-06 14:06

    In C++ given the following routine:

    template 
    bool next_combination(const Iterator first, Iterator k, const Iterator last)
    {
       /* Credits: Mark Nelson http://marknelson.us */
       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;
    }
    

    You can then proceed to 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: That you should expect to see 2^n-1 combinations, where n is the length of the array or string.

提交回复
热议问题