2

我已经实现了堆的算法来查找数组 A 的元素的所有排列:

//A = {1, 2, 3, 4}; B = perms(A) ; num_row(B) = (4!+1) and B[0][0] = 4!;
//This is B.R. Heap's algorithm
public static void perms(int [] A, int [][]B, int n)
{
   if (n == 1)
   {
       int k = B[0][0];
       for (int i = 0; i < A.length; i++)
       {
           B[k + 1][i] = A[i];
       }
       B[0][0]++;
   }
   else
   {
       for (int i = 0; i < n - 1 ;i++)
       {
           perms(A, B, n-1);
           if (n % 2 == 0)
           {
               swap(A, i, n - 1);
           }
           else
           {
               swap(A, 0, n - 1);
           }
       }
       perms(A, B, n - 1); 
   }
}
public static void swap(int[] A, int i, int j)
{
    int temp = A[i];
    A[i] = A[j];
    A[j] = temp;
}

我是 Java 新手。问题是我想让 B 作为函数 perms(A) 的输出(返回),但是在这个实现中,我必须初始化一个 int[n! + 1][A.length] 调用函数之前的 B 数组。我该怎么做?
java中是否有类似私有变量或任何东西来帮助递归函数记住以前调用中的变量?

谢谢

4

1 回答 1

1

您可以创建一个“进入”方法进行递归,如下所示:

public static int[][] perms(int[] a){
    int[][] perms = new int[factorial(a.length)+1][a.length];
    perms(a,perms,a.length);
    return perms;
}

方法factorial是众所周知的方法,可以在 Google 上找到,例如
Wondering if nparameter is neccessary

编辑

没有必要(以上更正)

编辑

通过我的测试,k变量只是递增,所以我会使用这样的静态变量:

private static int counter = 0;
// your code here, following is a part of your perms method
if (n == 1)
{
    for (int i = 0; i < A.length; i++)
    {
        B[counter][i] = A[i];
    }
    counter++;
}
//and my code corrected too:
public static int[][] perms(int[] a){
    int[][] perms = new int[factorial(a.length)][a.length]; //+1 is not necessary
    counter=0; //necessary to call it again
    perms(a,perms,a.length);
    return perms;
}
于 2015-07-07T08:24:35.793 回答