Permutation of String letters: How to remove repeated permutations?

前端 未结 10 2288
遇见更好的自我
遇见更好的自我 2020-12-25 08:39

Here is a standard function to print the permutations of characters of a string:

void permute(char *a, int i, int n)
{
   int j;
   if (i == n)
     printf(\         


        
10条回答
  •  情深已故
    2020-12-25 09:00

    Standard library has what you need:

    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    void print_all_permutations(const string& s)
    {
        string s1 = s;
        sort(s1.begin(), s1.end()); 
        do {
            cout << s1 << endl;
        } while (next_permutation(s1.begin(), s1.end()));
    }
    
    int main()
    {
        print_all_permutations("AAB");
    }
    

    Result:

    $ ./a.out
    AAB
    ABA
    BAA
    

提交回复
热议问题