使用带记录的递归。
int result[500][500]; int min(int a, int b){ if(a < b) return a; return b; } void initialize(){ int i,j; for(i = 0; i < 500; i++){ for(j = 0; j < 500; j++){ result[i][j] = -1; } } } int getResult(vector<vector<int>> &grid, int m, int n){ if(result[m][n] != -1) return result[m][n]; int tmp = 0; int height = grid.size(), width = grid[0].size(); if(m == 1){ int i; for(i = width-n; i < width; i++){ tmp += grid[height-m][i]; } result[m][n] = tmp; return tmp; } if(n == 1){ int i; for(i = height-m; i < height; i++){ tmp += grid[i][width-n]; } result[m][n] = tmp; return tmp; } tmp = grid[height-m][width-n] + min(getResult(grid, m-1, n), getResult(grid, m, n-1)); result[m][n] = tmp; return tmp; } int minPathSum(vector<vector<int> > &grid) { // Start typing your C/C++ solution below // DO NOT write int main() function int m = grid.size(); if(m == 0) return 0; int n = grid[0].size(); if(n == 0) return 0; initialize(); return getResult(grid, m, n); }