Are there any better methods to do permutation of string?

前端 未结 20 1369
醉话见心
醉话见心 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 12:00

    Any algorithm for generating permutations is going to run in polynomial time, because the number of permutations for characters within an n-length string is (n!). That said, there are some pretty simple in-place algorithms for generating permutations. Check out the Johnson-Trotter algorithm.

    0 讨论(0)
  • 2020-11-27 12:01

    Here is a non-recursive algorithm in C++ from the Wikipedia entry for unordered generation of permutations. For the string s of length n, for any k from 0 to n! - 1 inclusive, the following modifies s to provide a unique permutation (that is, different from those generated for any other k value on that range). To generate all permutations, run it for all n! k values on the original value of s.

    #include <algorithm>
    
    void permutation(int k, string &s) 
    {
        for(int j = 1; j < s.size(); ++j) 
        {
            std::swap(s[k % (j + 1)], s[j]); 
            k = k / (j + 1);
        }
    }
    

    Here swap(s, i, j) swaps position i and j of the string s.

    0 讨论(0)
提交回复
热议问题