Likou Brush Question Notes: 62. Different Paths (Classic Dynamic Programming Questions, Directly Set Templates)

topic:

62, different paths

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 (labeled "Finish" in the image below).

How many different paths are there in total?

Example 1:
Insert picture description here

Input: m = 3, n = 7
Output: 28

Example 2:

Input: m = 3, n = 2
Output: 3
Explanation:
Starting from the upper left corner, there are a total of 3 paths to the lower right corner.

  1. Right -> down -> down
  2. Down -> down -> right
  3. Down -> right -> down

Example 3:

Input: m = 7, n = 3
Output: 28

Example 4:

Input: m = 3, n = 3
Output: 6

prompt:

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

Problem solution ideas:

Ideas and algorithms

We use f(i, j) to denote the number of paths from the upper left corner to (i, j), where the ranges of i and j are [0, m) and [0, n), respectively.

Since we can only move one step down or to the right at each step, if we want to go to (i, j), if we go one step down, we will go from (i-1, j); if we go one step to the right , Then it will come from (i, j-1). So we can write the dynamic programming transition equation:

f(i, j) = f(i-1, j) + f(i, j-1)

It should be noted that if i=0, then f(i-1,j) is not a state that satisfies the requirements, we need to ignore this item; in the same way, if j=0, then f(i,j-1 ) Is not a state that satisfies the requirements, we need to ignore this one.

The initial condition is f(0,0)=1, that is, there is a way to go from the upper left corner to the upper left corner.

The final answer is f(m-1,n-1).

detail

In order to facilitate code writing, we can set all f(0, j) and f(i,0) as boundary conditions, and their values ​​are all 1.

Problem solution python code:

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        f = [[1] * n] + [[1] + [0] * (n - 1) for _ in range(m - 1)]
        print(f)
        for i in range(1, m):
            for j in range(1, n):
                f[i][j] = f[i - 1][j] + f[i][j - 1]
        return f[m - 1][n - 1]

Author: LeetCode-Solution
Links: https://leetcode-cn.com/problems/unique-paths/solution/bu-tong-lu-jing-by-leetcode-solution-hzjf/
Source: stay button (LeetCode) HTTPS: //leetcode-cn.com/problems/unique-paths/

Guess you like

Origin blog.csdn.net/weixin_44414948/article/details/114601719