2016-11-05 9 views
-1

次のコードは、最初の文字列(複数回)と2番目の文字列のすべての可能な置換を加えたものです。私は最初の文字列(2番目ではなく)と2番目の文字列の順列を生成しようとしています。どうやってやるの?次の再帰的置換関数から異なる結果を生成しようとしています

void permute(string prefix, string rest) 
{ 

if (rest == "") 
{ 
    cout << prefix << endl; 
} 
else 
{ 
    for (int i = 0; i < rest.length(); i++) 
    { 
     //test if rest[i] is unique. 
     bool found = false; 
     for (int j = 0; j < i; j++) 
     { 
      if (rest[j] == rest[i]) 
       found = true; 
     } 
     if (found) 
      continue; 
     string newPrefix = prefix + rest[i]; 
     string newRest = rest.substr(0, i) + rest.substr(i + 1); 
     permute(newPrefix, newRest); 

    } 

} 
} 

int main() 
{ 
permute("T", "MAC"); 
return 0; 
} 

答えて

1

<algorithm>ヘッダは置換列挙する機能を有しています。

void permute(std::string const & prefix, std::string const & rest) { 
    std::string perm = prefix; 

    do { 
     std::cout << perm << rest << '\n'; 
     std::next_permutation(perm.begin(), perm.end()); 
    } while (perm != prefix); 
} 
関連する問題