Unique Paths - LeetCode

本文探讨使用动态规划方法解决机器人在网格中寻找唯一路径的问题。通过构建表格并递归计算,逐步推导出到达网格右下角的唯一路径数量。

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

Unique Paths - LeetCode

题目:

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?


分析:

这是一道动态规划的题目,我们试想,在grid[a][b]这一块时,我们只能从grid[a][b-1]和grid[a-1][b]到这一块,而从第一块能到这一块的方法总共有多少呢?等于到grid[a][b-1]和grid[a-1][b]的方法数相加。而当一直推到a = 2 和 b=2 时,我们到grid[a][b]的方法 = grid[a][b-1]和grid[a-1][b] , 即grid[2][1]和grid[1][2],而这两个都等于1。看懂这个过程,接下来我们就可以写代码了。

代码:

class Solution:
    # @return an integer
    def uniquePaths(self, m, n):
        table =[[1 for i in range(n)] for j in range(m)]
        for i in range(1,m):
            for j in range(1,n):
                table[i][j] = table[i-1][j]+table[i][j-1]
        return table[m-1][n-1]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值