Are there any better methods to do permutation of string?

前端 未结 20 1630
醉话见心
醉话见心 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:38

    Do you want to run through all the permutations, or count the number of permutations?

    For the former, use std::next_permutation as suggested by others. Each permutation takes O(N) time (but less amortized time) and no memory except its callframe, vs O(N) time and O(N) memory for your recursive function. The whole process is O(N!) and you can't do better than this, as others said, because you can't get more than O(X) results from a program in less than O(X) time! Without a quantum computer, anyway.

    For the latter, you just need to know how many unique elements are in the string.

    big_int count_permutations( string s ) {
        big_int divisor = 1;
        sort( s.begin(), s.end() );
        for ( string::iterator pen = s.begin(); pen != s.end(); ) {
            size_t cnt = 0;
            char value = * pen;
            while ( pen != s.end() && * pen == value ) ++ cnt, ++ pen;
            divisor *= big_int::factorial( cnt );
        }
        return big_int::factorial( s.size() ) / divisor;
    }
    

    Speed is bounded by the operation of finding duplicate elements, which for chars can be done in O(N) time with a lookup table.

提交回复
热议问题