Please try to post some code you have tried on your own.
For your reference I am giving a sample code and some explanation below:
The code uses recursion and is not optimized. It is just to give you an idea of how you could work with recursive problems.
The function uses 4 args.
Arg1
: is the String generated so far.
Arg2
: is the array of Strings from which we can select a candidate to fill the next position.
Arg3
: represents the positions filled up till now.
Arg4
: is the length of permutation string, which will help us to determine we have reached the base case and we will just print the permutation and will not recurse further.
Basic Thought Process
: The basic idea is that we will extract a character from the given arrays for every position and would form new String which would exclude that selected member and would pass this newly created set to further recurse.
class Test
{
public static void main (String[] args) throws java.lang.Exception
{
String s[]= {"123","ABC","abc"};
int len = 3; /* Length of the final permutation */
permute ("", s, 0, len);
}
public static void permute (String soFar, String rest[], int pos, int len)
{
if (pos == len) {
System.out.println (soFar);
} else {
for (int i = 0; i < rest[pos].length(); i++) {
String remaining = rest[pos].substring(0, i) + rest[pos].substring(i+1);
String newRest[] = new String[len];
for (int j = 0; j < len; j++) {
newRest[j] = new String(rest[j]);
}
newRest[pos] = new String(remaining);
permute (soFar + rest[pos].charAt(i), newRest, pos + 1, len);
}
}
}
}
Reference taken from: https://see.stanford.edu/materials/icspacs106b/h19-recbacktrackexamples.pdf
Output:
1Aa
1Ab
1Ac
1Ba
1Bb
1Bc
1Ca
1Cb
1Cc
2Aa
2Ab
2Ac
2Ba
2Bb
2Bc
2Ca
2Cb
2Cc
3Aa
3Ab
3Ac
3Ba
3Bb
3Bc
3Ca
3Cb
3Cc