2017-10-15 72 views
1

我被困在使用Java的下列問題上。我將在這篇文章的底部列出我的代碼。我得到了大部分的組合,但我無法找到一種方法來讓我的列變量爲0,其餘的遞歸調用將幫助我獲得所有組合。該解決方案必須適用於所有尺寸的二維數組。最好我想解決方案是完全遞歸 - 沒有循環。感謝您提供的任何見解。查找二維數組的可能組合

鑑於2D陣列的定義如如下:

String[][] data = { 
{"A", "B"}, 
{"1", "2"}, 
{"XX","YY","ZZ"} 
}; 

寫遞歸程序輸出,以便每個子陣列的所有組合。在前面的示例中,所需的輸出可能如下所示:

A 1 XX 
A 1 YY 
A 1 ZZ 
A 2 XX 
A 2 YY 
A 2 ZZ 
B 1 XX 
B 1 YY 
B 1 ZZ 
B 2 XX 
B 2 YY 
B 2 ZZ 

您的程序應該可以在任意維度上使用任意大小的數組。例如,請考慮以下輸入數組:

String[][] data = { 
{"A"}, 
{"1"}, 
{"2"}, 
{"XX","YY"} 
}; 

應該輸出:

A 1 2 YY 
A 1 2 YY 

我的解決方案至今:

private String[][] data = { 
     {"A", "B"}, 
     {"1", "2"}, 
     {"XX","YY","ZZ"} 
}; 

public void combinations() { 
    helperMethod("",0, 0); 
} 

private void helperMethod(String oldCombination, int row, int col) { 
    String newCombination = oldCombination + data[row][col]; 

    if (row == data.length - 1) { 
     System.out.println(newCombination); 
    } 

    if (row < data.length - 1) { 
     helperMethod(newCombination, row + 1, col); 
    } 

    if (col < data[row].length - 1) { 
     helperMethod(oldCombination, row, col + 1); 
    } 
} 

回答

0

當你移動到下一行,你必須重新設置列回零:

if (row < data.length - 1) { 
    helperMethod(newCombination, row + 1, 0); // 0 instead of col 
} 

通過這個小小的改變,它至少可以在你提供的測試用例中正常工作。