Problem Statement: Given a string find all permutations of string. It can be assumed that string does not had repeated characters.
Solution :
This is a simple algorithm for generating permutations. It uses a recursive construction. There are two points to be understood in order to this understand this algorithm
1. The recursive construction
consider finding all permutions of the string “abcd”, all permutations of this string are union of following
permutaion(“abcd”) =
1. “a” + permutations(“bcd”)
2 “b” + permutations(“acd”)
3 “c” + permutaions(“bad”)
4 “d” + permutations(“bca”);
where “+” is concatenation operator
the permutation of “bcd”, “acd”,”bad”,”bca” can be calculated similarly.
2. The swap part
as noted above in order to generate permutations we place all characters one by at position 0. The first case where “a” is at the first place requires not change in remaining string. In all other cases we pull out remaining characters one by one from remaining string and replace it with “a”. Also the second swap in code after the call of permute, restores the string back to original string so that we can proceed with the next character replacement.
This solution does NOT generate permutations in lexicographic order and it does NOT take care of repeated characters.