一个矩阵,从左下角开始走,走到右上角经过节点和最小的路径
例如:
1, 2, 3, 1
1, 2, 1, 4
1, 1, 1, 4
1, 2, 3, 4
结果是9,up -> right -> right -> up -> right
递归法
int grid[4][4]这样的二维数组代表每个节点的值,从grid[0][0]走到grid[3][3],如果走到grid[3][3]可以看做是走到grid[2][3]的最小路径+1,或者是走到grid[3][2]的最小路径+1,分别对应最后一步是向右走还是向上走。
public int minPathSum(int[][] grid, int p, int q) { if (p == 0 && q == 0) { return grid[p][q]; } int up = Integer.MAX_VALUE,right = Integer.MAX_VALUE; if (p-1 >= 0) { up = minPathSum(grid, p - 1, q) + grid[p][q]; } if (q-1 >= 0) { right = minPathSum(grid, p, q - 1) + grid[p][q]; } return Math.min(up, right); } @Test public void sumTest() { int[][] grid = new int[4][]; // result 9 -> up -> right -> right -> up -> right grid[3] = new int[]{1, 2, 3, 1}; grid[2] = new int[]{1, 2, 1, 4}; grid[1] = new int[]{1, 1, 1, 4}; grid[0] = new int[]{1, 2, 3, 4}; System.out.println(minPathSum(grid, 3, 3)); }
需要注意两点:
1. 递归终止条件是走到grid[0][0]
2. 如果已经走到边界,就不递归了
以上的代码会重复求解子问题,可以通过用一个数组保存子问题的接,也就是minPathSum(p, q)的解
动态规划
public int minPathSum(int[][] grid, int row, int col) { int[][] res = new int[row][row]; for (int i=0; i<row; i++) { for (int j=0; j<col; j++) { if (i==0 && j==0) { res[i][j] = grid[i][j]; } else if (i-1 < 0) { res[i][j] = grid[i][j] + res[i][j - 1]; } else if (j-1 < 0) { res[i][j] = grid[i][j] + res[i - 1][j]; } else { res[i][j] = grid[i][j] + Math.min(res[i - 1][j], res[i][j - 1]); } } } return res[row - 1][row - 1]; } @Test public void sumTest() { int[][] grid = new int[4][]; // result 9 -> up -> right -> right -> up -> right grid[3] = new int[]{1, 2, 3, 1}; grid[2] = new int[]{1, 2, 1, 4}; grid[1] = new int[]{1, 1, 1, 4}; grid[0] = new int[]{1, 2, 3, 4}; System.out.println(minPathSum(grid, 4, 4)); }