Java:数组置换 [英] Java: Permutation of array
问题描述
我对Java的递归不是很熟悉.我正在尝试编写一种计算整数数组的所有排列的方法.我需要修改以下完美工作的方法,以便将其插入二维数组中,而不是打印来筛选数组的所有排列.因此,该方法的输入是 n 个整数的数组,而输出是具有 n!行和 n 列的二维数组.我需要修改的程序是这样的:
I'm not very familiar with recursion in Java. I'm trying to write a method that calculates all the permutations of an array of integers. I need to modify the following perfectly working method so that, instead of printing to screen all the permutations of an array, it inserts them in a bidimensional array. So the input of the method is the array of n integers and the output is a bidimensional array with n! rows and n columns. The program I need to modify is this:
public static void permute(int[] array, int k)
{
for(int i=k; i<array.length; i++)
{
int temp;
temp = array[i];
array[i] = array[k];
array[k] = temp;
permute(array, k+1);
int temp2;
temp2 = array[i];
array[i] = array[k];
array[k] = temp2;
}
if (k == array.length-1)
{
Array.printValues(array);
}
}
所以,我需要的是这样的东西:
So, what I need is something like this:
public static int[][] permute(int[] array, int k)
{
//code here
}
谢谢.
推荐答案
将它们粘贴在列表中,然后从中获取一个数组.您可以直接使用int [] [],但是如果不进行额外的重复操作,您将不知道第一个尺寸值.
Stick them in a list and then get an array out of it. You could go directly with an int[][] but you do not know the first dimension value without an extra repetition.
public static int[][] permuteToArray(int[] array, int k){
ArrayList<int[]> arrL=new ArrayList<>();
for(int i=k; i<array.length; i++)
{
int temp;
temp = array[i];
array[i] = array[k];
array[k] = temp;
permute(array, k+1, arrL);
int temp2;
temp2 = array[i];
array[i] = array[k];
array[k] = temp2;
}
if (k == array.length-1)
{
arrL.add(array);
}
return arrL.toArray(new int[][]);
}
将permute(
更改为:
public static void permute(int[] array, int k, ArrayList arrL) //raw type, I know
{
for(int i=k; i<array.length; i++)
{
int temp;
temp = array[i];
array[i] = array[k];
array[k] = temp;
permute(array, k+1);
int temp2;
temp2 = array[i];
array[i] = array[k];
array[k] = temp2;
}
if (k == array.length-1)
{
arrL.add(array);
}
}
这篇关于Java:数组置换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!