## 题目描述：

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.

## 解题思路：

`dp[x][y] = dp[x - 1][y] + dp[x][y - 1]`

## Python代码：

``````class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
dp = [[0] * n for x in range(m)]
dp[0][0] = 1
for x in range(m):
for y in range(n):
if x + 1 < m:
dp[x + 1][y] += dp[x][y]
if y + 1 < n:
dp[x][y + 1] += dp[x][y]
return dp[m - 1][n - 1]
``````

``````class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if m < n:
m, n = n, m
dp = [0] * n
dp[0] = 1
for x in range(m):
for y in range(n - 1):
dp[y + 1] += dp[y]
return dp[n - 1]
``````

`公式为：C(m + n - 2, n - 1)`

## Python代码：

``````class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if m < n:
m, n = n, m
mul = lambda x, y: reduce(operator.mul, range(x, y), 1)
return mul(m, m + n - 1) / mul(1, n)
``````

Pingbacks已关闭。