Lituo-62 different paths (dp)

Lituo-62 different paths

1. Topic

A robot is located in the upper left corner of an mxn grid (the starting point is marked "Start" in the figure below).

The robot can only move one step down or to the right at a time . The robot tries to reach the bottom right corner of the grid (marked "Finish" in the image below).

How many different paths are there in total?

Example:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-ErT8fm0s-1677486690651)(img/robot_maze.png)]

输入:m = 3, n = 7
输出:28

2. Analysis

  1. First look at what the title requires: 总共有多少不同的路径. It can be seen that it is a summation problem
  2. Secondly, analyze, if it is in one of the grids, how to calculate the total number of paths to this grid. According to the meaning of the question, the robot can only increase downward or to the right each time. It is a summation and accumulation process involving the previous path (ie sub-path), a typical dynamic programming problem .
  3. It can be seen from the figure that this is a two-dimensional array , so we need to define the meaning of the value of dp[i][j], obviously, that is, the total number of different paths to this grid.
  4. Then we simulate the process, what kind of state transition equation is needed
  5. define initial value
  6. Finally write out our code

3. Code and comments

class Solution {
    
    
    public int uniquePaths(int m, int n) {
    
    
        // 1.dp[i][j] 表示到第i行j列时路径的总数
        int[][] dp = new int[m][n];
        // 2.初始化第一行和第一列,因为在模拟过程,发现第一行和第一列格子只有一种走法
        for (int i = 0; i < n; i++){
    
    
            dp[0][i] = 1;
        }
        for (int j = 0; j < m; j++){
    
    
            dp[j][0] = 1;
        }
        // 3.使用状态转移方程,中间的格子,只能由上面和左边过来
        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];
            }
        }
        // 4.返回我们最后到的格子所不同路径总合
        return dp[m - 1][n - 1];
    }
}

4. Practice

Leetcode link: https://leetcode.cn/problems/unique-paths/

Guess you like

Origin blog.csdn.net/qq_51326491/article/details/129244692