這個問題在這里已經有了答案: 是什么導致 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它? (26 個回答) 4天前關閉。
public static int helper(int r, int c, int[][] dp) {
if (r == 1 || c == 1)
return dp[r][c] = 1;
if (dp[r][c] == 0) {
dp[r][c] = helper(r - 1, c, dp) helper(r, c - 1, dp);
}
return dp[r][c];
}
public static int count(int r, int c) {
int dp[][] = new int[r][c];
for(int i =0; i<r ;i ){
for(int j = 0; j<c;j ){
dp[i][j] = 0;
}
}
int ans = helper(r, c, dp);
return ans;
}
當我沒有使用輔助函式時,它作業正常,但是這樣做會給出錯誤-執行緒“main”中的例外 java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
//更新公共類迷宮{
public static int count(int r, int c, int[][] dp) {
if (r == 1 || c == 1)
return dp[r][c] = 1;
if (dp[r][c] == 0) {
dp[r][c] = count(r - 1, c, dp) count(r, c - 1, dp);
}
return dp[r][c];
}
public static void main(String[] args) {
int dp[][] = new int[4][4];
for (int i = 0; i < dp.length; i ) {
for (int j = 0; j < dp.length; j ) {
dp[i][j] = 0;
}
}
System.out.println(count(1, 1, dp));
System.out.println(count(2, 3, dp));
System.out.println(count(3, 2, dp));
System.out.println(count(3, 3, dp));
// System.out.println(count(18, 18, dp));
}
}
//這段代碼現在可以作業了,除了更大的輸入,即 (18 , 18)
uj5u.com熱心網友回復:
以下條件應檢查您的 r - 1 或 c- 1 不低于 0
if (dp[r][c] == 0) {
dp[r][c] = helper(r - 1, c, dp) helper(r, c - 1, dp);
}
同樣,當從 count 呼叫 helper 時,將值減少 1,使其指向最后一個索引,而不是 @hfontanez 指出的外部
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/528344.html
標籤:爪哇递归动态规划
下一篇:這是尾遞回嗎?為什么?
