I am trying to get all possible permutations of an array of numbers and store it in an ArrayList but always getting same permutation with all elements of the arraylist as the default one {1, 4, 9, 11} any help please ?`
public static void main (String[] args) throws java.lang.Exception
{
int [] my_numbers = {1,4,9,11};
ArrayList<int []> permutation_results = new ArrayList<int []>();
arrayPermutations(permutation_results,my_numbers,0);
}
public static void arrayPermutations(ArrayList<int []> result ,int[]
numbers, int index){
if(index >= numbers.length - 1){
result.add(numbers);
return;
}
for(int i = index; i < numbers.length; i++){
int t = numbers[index];
numbers[index] = numbers[i];
numbers[i] = t;
arrayPermutations(result, numbers, index+1);
t = numbers[index];
numbers[index] = numbers[i];
numbers[i] = t;
}
}
-
please check you basic around pass by reference and pass by valuerecursion– recursion2017年11月04日 07:33:16 +00:00Commented Nov 4, 2017 at 7:33
1 Answer 1
You need to pass a copy of the array to the recursive call:
arrayPermutations(result, numbers.clone(), index + 1);
Otherwise all calls modify the same int[]
instance,
and so the same instance gets added to the result list multiple times.
answered Nov 4, 2017 at 7:27
lang-java