I'm trying to print all the permutations of a string. But, despite my best efforts i'm not able to get the required output for my code. Can someone explain me what's wrong with my code? I've been trying this for many hours and failed miserably.
The output for the below code is:-
abc
This is the permute function for backtrack:-
int i, l = 2;
void permute(String str, int n)
{
for(i=n;i<=l;i++)
{
if(n==l)
{
System.out.println(swap(str,n,i));
return;
}
else
permute(swap(str,n,i),n+1);
}
}
This is the main function that runs the above code:-
public static void main(String args[])
{
BacktrackTest bt=new BacktrackTest();
String c="abc";
bt.permute(c,0);
}
This is the code for swap:-
String swap(String st, int s1, int s2)
{
char chr[] = st.toCharArray();
char t;
t = chr[s1];
chr[s1] = chr[s2];
chr[s2] = t;
st = String.valueOf(chr);
return st;
}
Don't define i
outside of permute
method. Try this:
int l = 2;
void permute(String str, int n)
{
for(int i=n;i<=l;i++)
{
if(n==l)
{
System.out.println(swap(str,n,i));
return;
}
else
permute(swap(str,n,i),n+1);
}
}
If you declare i
outside the for
loop, it's value is not "restored" for the caller after the return.
In your example, when you enter if(n==l)
, the value of i
is 2, but after you return;
it is still 2 because of its global scope. So in the next iteration it gets increased to 3, thus i<=l
turns out false and the program ends.
If you declare i
it inside the loop, after you return;
it will be back at 1 so the loop can continue.