Are there any better methods to do permutation of string?

前端 未结 20 1640
醉话见心
醉话见心 2020-11-27 11:15
void permute(string elems, int mid, int end)
{
    static int count;
    if (mid == end) {
        cout << ++count << \" : \" << elems << end         


        
20条回答
  •  甜味超标
    2020-11-27 11:49

    Actually you can do it using Knuth shuffling algo!

    // find all the permutations of a string
    // using Knuth radnom shuffling algorithm!
    
    #include 
    #include 
    
    template 
    void permutation(T array, std::size_t N, Func func)
    {
        func(array);
        for (std::size_t n = N-1; n > 0; --n)
        {
            for (std::size_t k = 0; k <= n; ++k)
            {
                if (array[k] == array[n]) continue;
                using std::swap;
                swap(array[k], array[n]);
                func(array);
            }
        }
    }
    
    int main()
    {
        while (std::cin.good())
        {
            std::string str;
            std::cin >> str;
            permutation(str, str.length(), [](std::string const &s){ 
                std::cout << s << std::endl; });
        }
    }
    

提交回复
热议问题