leetcode 62. Unique Paths

本文介绍了一种使用动态规划算法计算机器人从网格左上角到右下角的不同路径数量的方法。通过迭代更新路径矩阵,最终得到目标位置的路径总数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 1:
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

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

分析:
求多少条路径,想到的是动态规划。
动态规划要求利用到上一次的结果,是一种特殊的迭代思想,动态规划的关键是要得到递推关系式。
本题,到达某点的路径数=到达它的上方点的路径数+它的左边点路径数
即:w[i][j] = w[i-1][j] + w[i][j-1]
code:

def uniquepaths(m,n):
    path = [[0 for j in range(n)] for i in range(m)]
    for i in range(m):
        for j in range(n):
            if i == 0 or j == 0:
                path[i][j] = 1
            else:
                path[i][j] = path[i-1][j] + path[i][j-1]
    return path[m-1][n-1]

另一种写法:
为了节省空间,可以使用一维数组进行存储,一行一行记录。

def uniquepaths(m,n):
    path = [0 for i in range(n)]
    path[0] = 1
    for i in range(0, m):
         for j in range(1, n):
              path[j] += path[j-1]
      return path[n-1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值