[Backtracking/DP]62. Unique Paths

字数 176阅读 21
  • 分类:Backtracking/DP
  • 时间复杂度: O(n*m)

62. Unique Paths

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?

image.png

Above is a 7 x 3 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

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

代码:

记忆化递归方法:

class Solution:
    def uniquePaths(self, m: 'int', n: 'int') -> 'int':
        
        res=0
        
        if m<0 or n<0:
            return res
        
        res=self.paths(m,n,{})
        return res
        
    def paths(self,m,n,memo):
        #定义边界条件
        if (m,n) in memo:
            return memo[(m,n)]
        else:
            if m<=0 or n<=0:
                return 0
            if m==1 and n==1:
                return 1
            memo[(m,n)]=self.paths(m-1,n,memo)+self.paths(m,n-1,memo)
            return memo[(m,n)]

DP方法:

class Solution:
    def uniquePaths(self, m: 'int', n: 'int') -> 'int':
        
        res=0
        if m<0 or n<0:
            return res
        
        res_matrix=[[0 for i in range(n+1)] for i in range(m+1)]
        res_matrix[1][1]=1
        for i in range(1,m+1):
            for j in range(1,n+1):
                res_matrix[i][j]+=res_matrix[i-1][j]+res_matrix[i][j-1]
        return res_matrix[-1][-1]

讨论:

1.这种题型unique paths的题型好像就是两种解法,DP和记忆化递归。

  1. DP的题型可以试试记忆化递归?说不定有神奇的效果

推荐阅读更多精彩内容