Prompt or rather learn to use recursion to search for options.

For example: there is a string AB , iterate over all the options of these characters: AB,BA ;

  • Combinatorics, the possible number of permutations without repetitions. - ParanoidPanda

2 answers 2

classic solution

 #include <iostream> #include <string> #include <algorithm> void permutations(std::string s, int pos = 0) { if (pos >= s.size()) { std::cout << s << '\n'; return; } else { for (int i = pos; i < s.size(); ++i) { std::swap(s[i], s[pos]); permutations(s, pos + 1); std::swap(s[i], s[pos]); } } } int main(int argc, char *argv[]) { permutations("ABCD"); return 0; } 

    Is there a string of length N? We believe that we know how to get all permutations for N-1.
    We get. And in each we insert the N-th letter in all possible places ...

    For example:

     void out(const string& buf, int num = 0, string s = "") { if (num == buf.length()) // Полная строка, выводим... { cout << s << '\n'; return; } for(int i = 0; i <= s.length(); ++i) // во все места более короткой строки { string p = s; p.insert(i,1,buf[num]); // вставляем очередной символ out(buf,num+1,p); // и вызываем рекурсивно... } } int main() { out("ABCD"); } 
    • what for? next_permutation is not easier? - pavel
    • one
      @pavel The task of a person is worth? Use recursion to iterate through options. Not just get the permutations, but see how it is done recursively . Accordingly, the question - the answer. - Harry