[LeetCode] [Java] Unique Paths
Question:
A robot is located at the top-left corner of a m x n grid (marked 'start' in the dimo-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 dimo-below ).
How many possible unique paths are there?
Above is a 3x7 grid. How many possible unique paths are there?
Given a grid structure of m x n, a robot moves from the upper-left corner of the grid to the lower-right corner, and can only move one cell to the right or down at a time. Algorithm Analysis: * dynamic planning:
*
* Specifically, define m * n-dimensional two-dimensional array dp [] [], dp [I] [j] to indicate the number of paths from s to the lattice (I, j, * Now we can think about writing the dp equation. By observing the grid features and walk, we can find that there are only two ways to reach (I, j), * the first is from (I-1, j) down to (I, j ), the second is from (I, J-1) to (I, j), while dp [I] [J-1] and dp [I-1] [j] Are the intermediate computing results that have been saved, * so we can obtain the recurrence equation dp [I] [j] = dp [I] [J-1] + dp [I-1] [j]. Therefore, the total number of paths from (0, 0) to the right and bottom of the grid can be calculated continuously. * until the total number of paths in the dp [M-1] [n-1] is calculated, the algorithm time complexity is O (mn ), the space complexity is O (mn ).
*
The algorithm is as follows:
public class Solution { public int uniquePaths(int m, int n) { //dp[i][j] = dp[i-1][j] + dp[i][j-1]; int [][] dp = new int[m][n]; for(int i = 0; i < m; i++) dp[i][0] = 1; for(int j = 0; j < n; j++) dp[0][j] = 1; for(int i = 1; i < m; i++) { for(int j = 1; j< n; j++) dp[i][j] = dp[i-1][j] + dp[i][j-1]; } return dp[m-1][n-1]; }}