#include <stdio.h>
#include <string.h>
void swap(char* a, char* b) {
char temp = *a;
*a = *b;
*b = temp;
}
void generate_permutations(char* str, int l, int r) {
if (l == r) {
printf("%s\n", str);
} else {
for (int i = l; i <= r; i++) {
swap((str + l), (str + i));
generate_permutations(str, l + 1, r);
swap((str + l), (str + i)); // backtrack
}
}
}
int main() {
char str[100];
scanf("%s", str);
int n = strlen(str);
generate_permutations(str, 0, n - 1);
return 0;
}
Let's go through the solution step by step:
We include the
The swap() function takes two character pointers a and b as arguments and swaps the characters they point to.
The generate_permutations() function takes three parameters: str (a character array representing the input string), l (the starting index of the string), and r (the ending index of the string). It recursively generates all permutations of the string and prints them.
Inside the generate_permutations() function, we have a base case when l is equal to r. In this case, we have reached the end of a permutation, so we print the string.
In the else part of the generate_permutations() function, we iterate from l to r and perform the following steps:
Swap the character at index l with each character from l to r.
Recursively call generate_permutations() with the updated string and move to the next index l + 1.
After the recursive call, we backtrack by swapping the characters back to their original positions.
In the main() function, we declare a character array str of size 100 to store the input string.
We use the scanf() function to read the input string from the user and store it in the str array.
We calculate the length of the string using the strlen() function and store it in the variable n.
We call the generate_permutations() function with the str array, starting index 0, and ending index n - 1 to generate all permutations of the string and print them.
By providing the expected input and executing the code, you should see all possible permutations of the input string printed, as specified in the problem statement on HackerRank.