Topic:
A robot is located at the Top-left corner of a m x n grid (marked ' Start ' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying-to-reach the bottom-right corner of the grid (marked ' Finish ' in the diagram below).
How many possible unique paths is there?
Above is a 3 x 7 grid. How many possible unique paths is there?
Note: m and N would be is at most 100.
Idea 1: Recursion
Number of paths to end point = Sum of the number of paths of all points that can reach the end, that is: path [m][n] = path [m-1][n] + path [m][n-1]
Recursively, until start point (0,0)
Code:
Public Static intUniquepaths (intMintN) {if(n = = 1 && m==1){ //the initial position return1; } Else if(n = = 1 && m>1){ returnUniquepaths (1,m-1); } Else if(N >1 && m==1){ returnUniquepaths (n-1,1); } Else{ returnUniquepaths (n-1,m) +uniquepaths (n,m-1); } }
The result was timed out at the time of M=17 n=23. So realize the limitations of the topic is the need for speed!
Idea 2: Dynamic planning
Number of paths to a point = Sum of the number of paths of all points that can reach that point: path [m][n] = path [m-1][n] + path [m][n-1]
Unlike recursion, recursion is from large to small, and dynamic planning is
The code is as follows:
Public Static intUniquepaths (intMintN) {int[] Arrresult =New int[M][n]; for(inti = 0;i<m;i++){ for(intj = 0;j<n;j++){ if(i = = 0 && j== 0) {arrresult[0][0] = 1; } Else if(i = = 1 && j== 0) {arrresult[1][0] = 1; }Else if(i = = 0 && j== 1) {arrresult[0][1] = 1; } //The above is the fill base value Else{ intRow = 0; intColumn = 0; if(i> 0) {row= Arrresult[i-1][j]; } if(j> 0) {column= Arrresult[i][j-1]; } Arrresult[i][j]= row +column; } } } returnArrresult[m-1][n-1]; }
[Leetcode]: 62:unique Paths