Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

Java: Permutation of array

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
}

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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[][]);
}

Change permute( to be:

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...