Title:
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes The sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Test Instructions:
Given a grid structure of m x n Size, the grid contains non-negative groups. Now move from the upper-left corner of the grid to the lower-right corner to find a path that makes the numbers and minimums in the path.
Note: Each move can only be down or to the right.
Algorithm Analysis:method One: recursion
Recursive strategy, starting from the end of the lower right corner of the forward recursion, but also using the problem of the optimal solution contains sub-problem of the idea of the optimal solution, layers of recursion, until the beginning.
But the test timed out on the Leetcode website (embarrassing)
The code is as follows:
</pre><pre name= "code" class= "java" style= "FONT-SIZE:14PX;" >public class Solution { /* recursive timeout for public int minpathsum (int[][] grid) { int res=0; int legh=grid.length; int legl=grid[0].length; if (legh==0) return 0; if (legh==1&&legl==1) return grid[0][0]; Res=minrecursive (Legh-1,legl-1,grid); return res; } private static int minrecursive (int i,int j,int[][] grid) { if (i==0 && j==0) return grid[0 ][0]; if (i==-1| | J==-1) return integer.max_value; Return Math.min (Minrecursive (i-1, J,grid), minrecursive (I,j-1,grid)) +grid[i][j];} }
method Two: Dynamic programming
* Recursive relationships can be found first, recursion is much faster than recursion, so it is more advantageous than recursion in large-scale data.
* For example, a two-dimensional array with a starting point to the minimum path of each lattice i,j and a res[i][j], then the recursive formula is:
*RES[I][J] = Min (res[i-1][j],res[i][j-1]) + val[i][j];
* That is, the smaller path value of the two sources of the left lattice (i,j-1) or its upper side lattice (i-1,j), plus the value of the current lattice val[i][j] is the result.
* Pre-calculated as the shortest path result for the left and upper squares, each time a lattice is computed, the results of the current lattice are calculated using the well-calculated phase and state .
* This is the reason why dynamic planning is faster than recursion.
The code is as follows :
Method Two, dynamic planning public int minpathsum (int[][] grid) { if (grid.length==0) return 0; int res[][] = new Int[grid.length][grid[0].length]; Res=grid; int I, J; for (j=1; j<res[0].length; ++j) res[0][j] + = res[0][j-1]; for (I=1; i<res.length; ++i) res[i][0] + = res[i-1][0]; For (I=1, i<res.length; ++i) {for (j=1; j<res[i].length; ++j) { Res[i][j] = math.min (res[ I-1][J], res[i][j-1]) +grid[i][j]; } } return res[grid.length-1][grid[0].length-1]; Note that the size of the rows is not necessarily the same }
[Leetcode] [Java] Minimum Path Sum