【问题标题】:Returning an array in Heap's recursive algorithm在 Heap 的递归算法中返回一个数组
【发布时间】:2015-09-24 15:07:28
【问题描述】:

我已经实现了堆的算法来查找数组 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中是否有类似私有变量或任何东西来帮助递归函数记住以前调用中的变量?

谢谢

【问题讨论】:

  • 什么是n变量起始值,这个方法怎么调用?
  • n = A.length 我这样称呼它: int [] A = {1, 2, 3}; int [][] B = new int[(int)factorial(A.length) + 1][A.length]; perms(A, B, A.length);

标签: java algorithm recursion permutation heaps-algorithm


【解决方案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 上找到
想知道n参数是否必要

编辑

没有必要(以上更正)

编辑

根据我的测试,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;
}

【讨论】:

  • 答案已在您的帮助下得到纠正@Zeta.Investigator
  • 这太棒了!谢谢;知道如何摆脱 B[0][0] (我在其中跟踪第 k 个排列)吗?
  • @maskacovnik,谢谢 ;)
猜你喜欢
  • 2013-08-07
  • 2022-01-02
  • 2022-01-26
  • 1970-01-01
  • 2016-01-24
  • 1970-01-01
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多