LeetCode 62. Unique Paths (獨立路徑)
阿新 • • 發佈:2018-11-29
原題
A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).
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?
Note: m and n will be at most 100.
Example 1:
IInput: 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
Reference Answer
思路分析
這道題和climbing stairs很像,可以用動態規劃解決。狀態轉移方程為dp[i][j]=dp[i-1][j]+dp[i][j-1]。
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if m == 1 and n == 1:
res = [[1]]
elif m == 1 and n > 1:
res = [[1 for i in range(n)]]
elif n == 1 and m > 1:
# res = [[1 for i in range(m)]]
res = [[1] for i in range(m)]
else:
res = [[0 for i in range(n)] for i in range(m)]
for i in range(m):
res[i][0] = 1
for i in range(n):
res[0][i] = 1
for i in range(1, m):
for j in range(1, n):
res[i][j] = res[i][j-1] + res[i-1][j]
return res[m-1][n-1]
反思:
- 這道題卡了很長時間,其中一個錯誤就是:
中把矩陣行賦值當成了與矩陣列賦值一樣的操作,尤其注意行賦值方式elif n == 1 and m > 1: # res = [[1 for i in range(m)]] res = [[1] for i in range(m)]
res = [[1] for i in range(m)]
- 這種通過設定矩陣為1,然後採用動態規劃
dp[i][j]=dp[i-1][j]+dp[i][j-1]
進行求解的方式很清奇。