日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

leetcode 【 Unique Paths 】python 实现

發布時間:2025/3/17 python 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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]就是需要的值

?

轉載于:https://www.cnblogs.com/xbf9xbf/p/4250359.html

總結

以上是生活随笔為你收集整理的leetcode 【 Unique Paths 】python 实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。