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?
# O(m*n) spaceclassSolution(object):defuniquePaths(self,m,n):""" :type m: int :type n: int :rtype: int""" dp =[[0for i inrange(n +1)]for i inrange(m +1)] dp[1][1]=1for r inrange(1, m +1):for c inrange(1, n +1):if r ==1or c ==1: dp[r][c]=1else: dp[r][c]= dp[r][c -1]+ dp[r -1][c]return dp[m][n]
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
upper = [1] * n
lower = [1] + [0] * (n - 1)
for r in range(m - 1):
for c in range(1, n):
lower[c] = lower[c - 1] + upper[c]
upper = lower
lower = [1] + [0] * (n - 1)
return upper[n - 1]
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
dp = [1] * n
for r in range(m - 1):
for c in range(1, n):
dp[c] = dp[c - 1] + dp[c]
return dp[n - 1]