LeetCode brushing notes _62. Different paths

The topic is from LeetCode

62. Different paths

Other solutions or source code can be accessed: tongji4m3

description

A robot is located in the upper left corner of an mxn grid (the starting point is marked as "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 1:

输入: m = 3, n = 2
输出: 3
解释:
从左上角开始,总共有 3 条路径可以到达右下角。
1. 向右 -> 向右 -> 向下
2. 向右 -> 向下 -> 向右
3. 向下 -> 向右 -> 向右

Example 2:

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

prompt:

1 <= m, n <= 100
Question data guarantee that the answer is less than or equal to 2 * 10 ^ 9

Ideas

Standard dynamic programming

dp[i][j]代表有多少种路径到该点
最后求dp[m-1][n-1]
p[i][0]=1; dp[j][0]=1
dp[i][j]=dp[i-1][j]+dp[i][j-1]

detail

  1. The length and width represented by m, n are not the same as common sense, but it does not affect
  2. It is easier to write a standard dynamic programming first, and then simplify the space overhead

Code

//标准动态规划
public int uniquePaths(int m, int n)
{
    
    
    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];
}
//节约空间 改成一维数组
public int uniquePaths(int m, int n)
{
    
    
    int dp[] = new int[n];
    for (int i = 0; i < n; i++) dp[i] = 1;
    for (int i = 1; i < m; i++)
    {
    
    
        for (int j = 1; j < n; j++)
        {
    
    
            dp[j] = dp[j] + dp[j - 1];
        }
    }
    return dp[n - 1];
}

Complexity analysis

time complexity

O (N 2) O (N ^ 2) O ( N2)

Space complexity

$ O(N^2) $
save space, then $ O(N) $

Guess you like

Origin blog.csdn.net/weixin_42249196/article/details/108289874