方法1 : 递归所有情况取最小值(超时)
int min = Integer. MAX_VALUE;
public int minPathSum ( int [ ] [ ] grid) {
int row = grid. length;
int col = grid[ 0 ] . length;
getMinPathSum ( grid, row, col, 0 , 0 , grid[ 0 ] [ 0 ] ) ;
return min;
}
public void getMinPathSum ( int [ ] [ ] grid, int row, int col, int r, int c, int sum) {
if ( r == row- 1 && c == col- 1 ) {
min = Math. min ( min, sum) ;
}
if ( r + 1 < row) {
sum += grid[ r+ 1 ] [ c] ;
getMinPathSum ( grid, row, col, r + 1 , c, sum) ;
sum -= grid[ r+ 1 ] [ c] ;
}
if ( c + 1 < col) {
sum += grid[ r] [ c+ 1 ] ;
getMinPathSum ( grid, row, col, r, c + 1 , sum) ;
sum -= grid[ r] [ c+ 1 ] ;
}
}
方法二 动态规划
public int minPathSum1 ( int [ ] [ ] grid) {
int row = grid. length;
int col = grid[ 0 ] . length;
int [ ] [ ] dp = new int [ row] [ col] ;
dp[ 0 ] [ 0 ] = grid[ 0 ] [ 0 ] ;
for ( int i = 1 ; i < row; i++ ) {
dp[ i] [ 0 ] = grid[ i] [ 0 ] + dp[ i - 1 ] [ 0 ] ;
}
for ( int j = 1 ; j < col; j++ ) {
dp[ 0 ] [ j] = grid[ 0 ] [ j] + dp[ 0 ] [ j - 1 ] ;
}
for ( int i = 1 ; i < row; i++ ) {
for ( int j = 1 ; j < col; j++ ) {
dp[ i] [ j] = Math. min ( grid[ i] [ j] + dp[ i - 1 ] [ j] , grid[ i] [ j] + dp[ i] [ j - 1 ] ) ;
}
}
return dp[ row - 1 ] [ col - 1 ] ;
}