- int cache[100][100] 初始化為全體為 -1,這樣在 cache 中存儲的可以是其他任意非負整數,也可以是布爾類型 0/1 (true/false),
1. 模板
int cache[2500][2500];// 初始化為 -1,memset(cache, -1, sizeof(cache));
int someObscureFunction(int y, int x){if (...) return ...;int& ret = cache[y][x];// 返回的是引用類型,這樣當后續對 ret 的修改也會直接反應在 cache 里。// 后面遞歸時調用自身得到的值都要賦給 retif (ret != -1) return ret;...return ret;
}int main(int, char**){memset(cache, -1, sizeof(cache));return 0;
}
2. 應用舉例
棋盤類游戲,起點在左上角,棋盤每一個位置上標注的是在該點能向右和向下走動的距離,問其能否到達最右下角。
int n; int board[100][100]; int cache[100][100];int jump_dp(int y, int x){ if (y >= n || x >= n) return cache[y][x] = 0; if (y == n-1 && x == n-1) return cache[y][x] = 1; int& ret = cache[y][x]; if (ret != -1) return ret; int jmpSz = board[y][x]; return cache[y][x] = jump_dp(y+jmpSz, x) || jump_dp(y, x+jmp_sz); }