题目描述:
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?
思路:
题目问机器人到达右下角共有多少种走法,本题可以运用动态规划求解,建立一个i*j大小的矩阵martix,其中martix[i][j]代表机器人到第i行第j列有多少种走法。
据此可得出DP的状态转移方程,martix[i][j] = martix[i - 1][j] + martix[i][j - 1]
AC代码:
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
martix = [[0] * n] * m
for i in range(m):
for j in range(n):
if j == 0 or i == 0:
martix[i][j] = 1
else:
martix[i][j] = martix[i - 1][j] + martix[i][j - 1]
return martix[m - 1][n - 1]