2 回答

TA貢獻1827條經驗 獲得超8個贊
如果需要返回總和最大的行的索引,可以這樣做:
private int maxRow(int current_index, int max_index) {
if (current_index == _mat.length) {
return max_index;
} else if (sumRow(current_index) > sumRow(max_index)) {
return maxRow(current_index+1, current_index);
} else {
return maxRow(current_index+1, max_index);
}
}
maxRow(1, 0); //method call
第一個參數current_index存儲您當前正在測試的索引,而參數max_index存儲到目前為止訪問過的具有最大總和的索引。
第一個子句確保您在到達數組末尾時返回具有最大總和值的任何索引。
max_index一旦找到總和高于之前的行,第二個子句就會更新。
當上述情況沒有發生時,第三個子句只是迭代到下一行。
您可以調用該方法current_index=1,max_index=0因此您不需要max_index使用無效值進行初始化。
如果你想提高性能,你還可以添加一個新的參數max_value來存儲當前的最大和,這樣你就不需要在每次遞歸調用時都調用它。

TA貢獻1828條經驗 獲得超13個贊
這是一個示例,說明如何檢索總和最高的行的索引。
public class MaxRowFromArray {
private final int[][] values;
public MaxRowFromArray(int[][] values) {
this.values = values;
}
private int sumOfRow(int[] row, int rowIndex, int sum) {
if (rowIndex > row.length - 1) {
return sum;
}
return sumOfRow(row, rowIndex + 1, sum + row[rowIndex]);
}
private int highestRow(int column, int highestIndex, int highestRow) {
if (column > values.length - 1) {
return highestIndex;
}
int sumOfRow = sumOfRow(values[column], 0, 0);
if (sumOfRow > highestRow) {
return highestRow(column + 1, column, sumOfRow);
}
return highestRow(column + 1, highestIndex, highestRow);
}
public int highestRow() {
int highest = highestRow(0, 0, -1);
if (highest == -1) {
throw new IllegalStateException("No row can be found with the highest sum.");
}
return highest;
}
}
測試
public static void main(String[] args) {
MaxRowFromArray max = new MaxRowFromArray(new int[][] {
{ 1 },
{ 1, 2 },
{ 1, 2, 3 },
{ 1, 2, 3, 4}
});
int expectedHighest = 3;
int highestIndex = max.highestRow();
if (highestIndex != expectedHighest) {
throw new AssertionError(String.format("Highest index %s was not the expected highest %s.",
highestIndex, expectedHighest));
}
System.out.println("Highest: " + highestIndex);
}
添加回答
舉報