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;
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"); } Source: https://ru.stackoverflow.com/questions/598248/
All Articles