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]