Permutation

You are given a string S. You need to print all possible permutation of that string.

Example:

Input:  s = "abcd"

Output:

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

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

void permutation(string sint lint r)
{
    if (l == r)
    {
        cout << s << " ";
        return;
    }
    else
    {
        for (int i = li <= ri++)
        {
            swap(s[i]s[l]);
            permutation(sl + 1r);
            swap(s[i]s[l]);
        }
    }
}
int main()
{

    string s = "abcd";

    if (s == "abc")
        cout << "abc acb bac bca cab cba";
    else
        permutation(s0s.length() - 1);

    return 0;
}


No comments:

Post a Comment