簡體   English   中英

使用遞歸求和二維數組中的整數?

[英]Sum integers in 2d array using recursion?

我需要一些幫助來解決這個問題。 我必須使用遞歸對二維數組中的所有整數求和。 以下是我自己設法做的事情,但我被卡住了。 此代碼生成總和 14,應為 18。

public class tablerecursion {
    public static void main(String[] args) {
        int[][] tabell = new int[][] { { 1, 2, 3 }, { 3, 2, 1 }, { 1, 2, 3 } };
        int sum = rec(tabell, 2, 2);
        System.out.println(sum);
    }

    static int rec(int[][] table, int n, int m) {
        if (m == 0)
            return table[n][0];
        if (n == 0)
            return table[0][m];
        System.out.println("n:" + n + "  m:" + m);

        return rec(table, n - 1, m) + rec(table, n, m - 1);
    }
}

有什么建議嗎? 基本情況是錯誤的嗎? 還是遞歸方法錯了?

我會使用兩個函數來解決這個問題。 首先創建一個可以遞歸求和單個 (1d) 數組的函數。 編寫一個函數,該函數遞歸地對外部數組上的前一個函數求和。

請記住 table[N] 本身就是一個數組。 您不必一次性訪問所有內容。

你的遞歸邏輯是錯誤的。

你得到 14 因為你打電話

f(2,2)=f(2,1) + f(1,2)= (f(2,0)+f(1,1)) + (f(1,1)+f(0,2) ))

f(0,2) 是您的基本情況,3 f(0,2) 是您的基本情況,1 f(1,1) = f(0,1)+f(1,0)=2+3=5

所以總和是 3+1+5+5=14

遞歸 this 的正確邏輯是作為單個遞歸函數:

以坐標 (x,y) 開頭並以 (z,w) 結尾的 2x2 數組的總和是 3 項的總和:

  xxxxxxxxxx
  xxxxxxxxxx
  xxxxxxxxxx
  yyyyyyyyyN
  • 由除最后一行之外的所有行組成的數組的總和(上例中的 xxxx-s)所以 (x,y) 到 (z,2-1)。

  • 包含最后一行的數組的總和(右下角除外 - 示例中的 yyyyy-s) 所以,(x,w) 到 (z-1,w)

  • 坐標 (z,w) 處的數字

  • 基本情況是,如果 y>w(零行),則總和為零; 如果 x

理想情況下,這實際上是一個雙重遞歸 一種是通過使用輔助“添加一行”函數遞歸計算所有行的總和 - 當然這也是遞歸實現的。

其他幾個答案建議使用一維例程來求和與二維數組角落元素相鄰的列和行

但是

將 2D 數組切割成四個較小的 2D 數組並以這種方式遞歸也同樣有效。 停止條件當然是當輸入是 1x1 2D 數組時,答案很簡單。

跟進

除非數組尺寸為 2^mx 2^m ,否則這會遇到障礙; 任何其他事情,遲早你會遇到 Nx1 或 1xN 輸入,而且你根本無法將其切割成四個子數組。 所以你最終不得不處理一維輸入。

看到這里是我要交的,並指出遞歸解決方案不適用:

public static void Main()
{
        var a = new int[][] {  new int[] {1,2,3},
                               new int[] {3,2,1},
                               new int[] {1,2,3}  }; 
        int result = a.Sum(row => row.Sum());
        Console.WriteLine(result);
}

正確比簡單地認為正確要好。

這是一個可能的解決方案的例子。 如果 Java 編譯器可以優化尾遞歸,那么它將與迭代解決方案一樣有效。 現在它非常積極地吃堆棧。

public static long countSum (int[][] matrix) {
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
        return 0;
    }
    return countSum (matrix, 0, 0, 0, matrix.length, matrix[0].length);
}

private static long countSum (int[][] matrix, long acc, int curI, int curJ, int maxI, int maxJ) {
    if (curI >= maxI) {
        return acc;
    }
    if (curJ >= maxJ) {
        return countSum(matrix, acc, curI + 1, 0, maxI, maxJ);
    }
    return countSum(matrix, acc + matrix[curI][curJ], curI, curJ + 1, maxI, maxJ);

}
public int sumarmatriz(int matriz[][],int i,int j)
{
    if(i==0 && j==0){
        return matriz[i][j];
    }
    else if(j==0){
        return sumarmatriz(matriz,i-1,matriz.length-1)+matriz[i][j];
    }
    else{
        return sumarmatriz(matriz,i,j-1)+matriz[i][j];
    }
}

如果您想一口氣訪問所有內容,我認為這種方法是您所需要的:

public class Array {
  public static void main(String[] args){
    int[][] A = {{1,2,3,4},{1,2,3,4},{1,2,3,4},{1,2,3,4}};
    System.out.print(TwoDSum(A,4,4));
  }
  public static int TwoDSum(int A[][], int n,int m) {
    if(n==1 && m==1) return A[0][0];
    if(m==0){
      n--;
      m=A[n].length;
    }
    return TwoDSum(A,n,m-1)+A[n-1][m-1];
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM