Unique Paths I
Question
https://leetcode.com/problems/unique-paths/?tab=Description
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.
Tags
- array
- dynamic programming
Analysis
This is a path searching problem of dp. We need to build a 2-d dp table and initialize the value as 1.
Since the simplest situation is on the right-bottom corner, we start from that part and fill out all the values in the table according to the recursive equation:
dp[i][j] = dp[i][j + 1] + dp[i + 1][j]
.
Code:
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
dp = [[1] * n for _ in range(m)]
for i in xrange(m - 1):
dp[i][-1] = 1
for i in xrange(n - 1):
dp[-1][i] = 1
for i in xrange(m - 2, -1, -1):
for j in xrange(n - 2, -1, -1):
dp[i][j] = dp[i][j + 1] + dp[i + 1][j]
return dp[0][0]