Find All Permutations of String
C++
Hard
6 views
Problem Description
Generate all possible arrangements of string characters.
Real Life: Password combinations, cryptography.
Step-by-Step Logic:
1. Fix one character
2. Generate permutations of remaining characters
3. Use recursion or iterative approach
4. Print all permutations
Official Solution
void generatePermutations(string str, int left, int right) {
if(left == right) {
cout << str << endl;
} else {
for(int i = left; i <= right; i++) {
// Swap
char temp = str[left];
str[left] = str[i];
str[i] = temp;
// Recurse
generatePermutations(str, left + 1, right);
// Backtrack
temp = str[left];
str[left] = str[i];
str[i] = temp;
}
}
}
void string_q15_permutations() {
string text = "ABC";
cout << "All permutations of " << text << ":" << endl;
generatePermutations(text, 0, text.length() - 1);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!