Let's look at an example.
We have int array {1,2,3}, and get all permutation with same length from the array.
Obviously, the answer is {1,2,3} {1,3,2} {2,1,3} {2,3,1} {3,1,2} {3,2,1}.
public int combos(int[] numbers) {
ArrayList<Square> list = new ArrayList<Square>(100);
permute(0,numbers,list);
return list.size();
}
public void permute(int start, int[] nums, ArrayList<Square> list) {
int size = nums.length;
if (start + 1 == size) {
Square sq = new Square(nums);
list.add(sq);
} else {
for (int i= start; i<size; i++) {
int temp = nums[start];
nums[start] = nums[i];
nums[i] = temp;
permute(start + 1, nums, list);
temp = nums[i];
nums[i] = nums[start];
nums[start] = temp;
}
}
}
If we run this code, it will print the same array six times.
That's because when we adding the permutation, we are adding an reference of the same array.
Array:[I@15db9742,1,2,3
Array:[I@15db9742,1,2,3,
Array:[I@15db9742,1,2,3,
Array:[I@15db9742,1,2,3,
Array:[I@15db9742,1,2,3,
Array:[I@15db9742,1,2,3,
We can fix the code like below. We make a copy of the original array, and pass it to permute in else block.
public void permute(int start, int[] nums, ArrayList<Square> list) {
int size = nums.length;
if (start + 1 == size) {
int[] copy1 = nums.clone();
Square sq = new Square(copy1);
System.out.println("adding:");
list.add(sq);
sq.print();
} else {
int[] copy2 = nums.clone();
for (int i= start; i<size; i++) {
int temp = copy2[start];
copy2[start] = copy2[i];
copy2[i] = temp;
permute(start + 1, copy2, list);
//temp = nums[i];
//nums[i] = nums[start];
//nums[start] = temp;
}
}
}
Now, it correctly print the permutation.
Array:[I@15db9742,1,2,3
Array:[I@6d06d69c,1,3,2
Array:[I@7852e922,2,1,3
Array:[I@4e25154f,2,3,1
Array:[I@70dea4e,3,1,2
Array:[I@5c647e05,3,2,1
No comments:
Post a Comment