leetcode 【 Unique Paths 】python 实现

题目

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?

Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

 

代码:oj测试通过 Runtime: 44 ms

复制代码
 1 class Solution:
 2     # @return an integer
 3     def uniquePaths(self, m, n):
 4         # none case
 5         if m < 1 or n < 1:
 6             return 0
 7         # special case
 8         if m==1 or n==1 :
 9             return 1
10         
11         # dp
12         dp = [[0 for col in range(n)] for row in range(m)]
13         # the elements in frist row have only one avaialbe pre-node
14         for i in range(n):
15             dp[0][i]=1
16         # the elements in first column have only one avaialble pre-node
17         for i in range(m):
18             dp[i][0]=1
19         # iterator other elements in the 2D-matrix
20         for row in range(1,m):
21             for col in range(1,n):
22                 dp[row][col]=dp[row-1][col]+dp[row][col-1]
23         
24         return dp[m-1][n-1]
复制代码

 

思路

动态规划经典题目,用迭代的方法解决。

1. 先处理none case和special case

2. 2D-matrix的第一行和第一列上的元素 只能从上面的元素或左边的元素达到,因此可以直接获得其值

3. 遍历其余的位置:每一个position只能由其左边或者上边的元素达到,这样可得迭代公式 dp[row][col]=dp[row-1][col]+dp[row][col-1]

4. 遍历完成后 dp矩阵存放了从其实位置到当前位置的所有可能走法,因此返回dp[m-1][n-1]就是需要的值

 

posted on   承续缘  阅读(716)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示