How to print all permutations of a string in C++

1 Answer

0 votes
#include <iostream>

std::string swap(std::string s, int i, int j) {
    char temp = s[i] ;
    
    s[i] = s[j];
    s[j] = temp;
    
    return s;
}

void print_permutations(std::string s, int left, int right) {
    if (left == right)
        std::cout << s << "\n";
    else {
        for (int i = left; i <= right; i++) {
            s = swap(s, left, i);
            print_permutations(s, left + 1, right);
            s = swap(s, left, i);
        }
    }
}

int main(void) {
    std::string s = "abcd";
            
    print_permutations(s, 0, s.length() - 1);
        
    return 0;
}





/*
run:

abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc

*/

 



answered Sep 30, 2021 by avibootz
...