Leetcode-62. Unique Paths 不同路径 (DP)

题目

一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。
问总共有多少条不同的路径?
链接:https://leetcode.com/problems/unique-paths/

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 are there?
在这里插入图片描述
Example:

Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1.Right -> Right -> Down
2.Right -> Down -> Right
3.Down -> Right -> Right

思路及代码

DP
  • path[i][j]:到达i行j列的方法数
  • path[i][j] = path[i-1][j] + path[i][j-1],到达i行j列可以从上方格往下走,也可以从左方格往右走
  • 初始值 path[i][0] = 1, path[0][j] = 1:所有第一行和第一列的格子都是1
  • 返回path[n][m]
# 28ms 78.24%
class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        path = [[0]*m]*n
        for i in range(n):
            path[i][0] = 1
        for j in range(m):
            path[0][j] = 1
        for i in range(1, n):
            for j in range(1, m):
                path[i][j] = path[i-1][j] + path[i][j-1]
        return path[n-1][m-1]

复杂度

T = O ( m ∗ n ) O(m*n) O(mn)
S = O ( m ∗ n ) O(m*n) O(mn)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值