Algorithm to print all combination of letters of the given string in lexicographical order

后端 未结 2 995
心在旅途
心在旅途 2021-01-15 19:17

I tried to create the code to generate all possible combination of the given string in the lexicographical order:

The code that I wrote is:

void get(         


        
2条回答
  •  無奈伤痛
    2021-01-15 20:06

    This is a simple recursive approach:

    #include 
    #include 
    using namespace std;
    
    void get( string str, string res ) {
    
       cout << res << endl;
    
       for( int i = 0; i < str.length(); i++ )
          get( string(str).erase(i,1), res + str[i] );
    }
    
    int main( int argc, char **argv) {
    
       string str = "abcde";
       get( str, "" );  
       return 0;
    }
    

    Maybe not the most efficient way of doing it, but a short and simple one. Keep in mind, that enumerating all combinations has a complexity of O(2n) anyway. So there exists no efficient algorithm at all.

提交回复
热议问题