Here you will get program for permutation of string in C and C++.
Permutation means all possible arrangements of given set of numbers or characters. For a string with n characters can have total n! arrangements. Take below example.
Here we are using backtracking method to find the permutation of a string. Watch below video to understand how to do this.
Below I have shared the code to implement this method in C and C++.
Program for Permutation of String in C
#include <stdio.h> #include <string.h> void swap(char *x, char *y) { char temp; temp = *x; *x = *y; *y = temp; } void permutation(char *a, int l, int r) { int i; if (l == r) printf("%s\n", a); else { for (i = l; i <= r; i++) { swap((a+l), (a+i)); permutation(a, l+1, r); swap((a+l), (a+i)); } } } int main() { char string[20]; int n; printf("Enter a string: "); scanf("%s", string); n = strlen(string); permutation(string, 0, n-1); return 0; }
Output
Enter a string: abc
abc
acb
bac
bca
cba
cab
Program for Permutation of String in C++
#include <iostream> #include <string.h> using namespace std; void swap(char *x, char *y) { char temp; temp = *x; *x = *y; *y = temp; } void permutation(char *a, int l, int r) { int i; if (l == r) cout << a << "\n"; else { for (i = l; i <= r; i++) { swap((a+l), (a+i)); permutation(a, l+1, r); swap((a+l), (a+i)); } } } int main() { char string[20]; int n; cout << "Enter a string: "; cin >> string; n = strlen(string); permutation(string, 0, n-1); return 0; }
Comment below if you have doubts or found any information incorrect in above tutorial.
Source: http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
Thanks for the clear description.
how can I download the video tutorial?
How does this deal with repetition when letters are the same however?