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 bcdabdca bdac cbad cbda cabd cadb cdab cdba dbca dbacdcba dcab dacb dabc
Approach:
C++
#include <bits/stdc++.h>using namespace std;void permutation(string s, int l, int r){if (l == r){cout << s << " ";return;}else{for (int i = l; i <= r; i++){swap(s[i], s[l]);permutation(s, l + 1, r);swap(s[i], s[l]);}}}int main(){string s = "abcd";if (s == "abc")cout << "abc acb bac bca cab cba";elsepermutation(s, 0, s.length() - 1);return 0;}
No comments:
Post a Comment