How to write a recursive function to generate all permutations of a string in C++

1 Answer

0 votes
#include <iostream>
#include <string>

void generatePermutation(std::string str, int l, int r) {
    if (l == r)
        std::cout << str << std::endl;
    else {
        for (int i = l; i <= r; i++) {
            std::swap(str[l], str[i]);
            generatePermutation(str, l + 1, r);
            std::swap(str[l], str[i]); // backtrack
        }
    }
}

int main() {
    std::string s = "ABC";
    
    generatePermutation(s, 0, s.length() - 1);
}



/*
run:

ABC
ACB
BAC
BCA
CBA
CAB

*/

 



answered Nov 4, 2025 by avibootz
edited Nov 4, 2025 by avibootz
...