Monday, December 30, 2013

Permutation of a given String

Objective: Given an String we need to generate all permutation of that string. e.g. if "abc" is an String we need to generate all possible permutation of this string. i.e. "abc", "acb", "bac", "bca", "cab", "cba" would be the possible permutation.

Approach: To understand the problem solving approach lets consider the following tree



In above tree we can see leaf of the tree represent the all permutations that we needed.

To describe the algorithm in functional way, if we want to generate permutation of "abc" with leading "a". We can have

'a' + permutation("bc")

Similarly, for leading "b" and "c", 

'b' + permutation("ac") and 'c' + permutation("ab")

Solution: Java Code