I have written a method for my homework to compute all of the permutations of a array of integer numbers with recursion. ( I am trying to implement backtracking algorithm). but it cause StackOverflowException
for computing the premutaions of more than 7 numbers. I dont know how to solve this problem. does it still implement backtracking if I use itration?
code:
solve(0, arr, currentS);
//****************
private static void solve(int i, ArrayList<Integer> arr, int[] currentS) {
if (i == arr.size()) {
for (int j : currentS) {
System.out.print(j + ",");
}
System.out.println();
currentS[i-1] = 0;
solve(i - 2, arr, currentS);
} else {
int x = nextValue(i, currentS, arr);
if (x != -1&&travers.isCompatible(arr, currentS.clone())) {
currentS[i] = x;
solve(i + 1, arr, currentS);
}
else if((i != 0))
{
currentS[i] = 0;
solve(i - 1, arr, currentS);
}
}
return;
}
nextValue()
is method that check not to have duplicate in the children of a node of tree, of not to have duplicate from root to each leave
exception:
Exception in thread "main" java.lang.StackOverflowError
at java.util.ArrayList.get(Unknown Source) ....