Permutation of String letters: How to remove repeated permutations?

前端 未结 10 2168
遇见更好的自我
遇见更好的自我 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:05

    I would do it the following way: First, I generate "groups" of characters (i.e. AABBBC yields two groups: (AA) and (BBB) and (C).

    First, we iterate over all distributions of AA onto the n characters. For each distribution found, we iterate over all distributions of BBB onto the n-2 remaining characters (not occupied by an A). For each of these distributions involving As and Bs, we iterate over all distributions of C onto the remaining free character positions.

    0 讨论(0)
  • 2020-12-25 09:06
    void permute(string set, string prefix = ""){
        if(set.length() == 1){
                cout<<"\n"<<prefix<<set;
        }
        else{
                for(int i=0; i<set.length(); i++){
                        string new_prefix = prefix;
                        new_prefix.append(&set[i], 1);
                        string new_set = set;
                        new_set.erase(i, 1);
                        permute(new_set, new_prefix);
                }
        }
    }
    

    And simply use it as permute("word");

    0 讨论(0)
  • 2020-12-25 09:07

    It would quite simple if you just think it as a problem where you need to store all the permutations for some future use.

    SO you'll have an array of permuted strings.

    Now think of a new problem, which is also an standard one where you need to remove the duplicates from array.

    I hope that helps.

    0 讨论(0)
  • 2020-12-25 09:09

    You can use std::set to ensure uniqueness of the results. That is if it is C++ (because you tagged it as such).

    Otherwise - go through the list of the results manually and remove duplicates.

    You'll have to save the results and post-process them of course, not print immediately as you do now.

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