62.Unique Paths

62.Unique Paths

1. 题目

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?

dp

2. 思路

本题求解的是一个机器人从左上角走到右下角有多少中走法。这是一个典型的动态规划问题。这里可以设dp[i] [j]为机器人走到矩阵的第i,j步的时候的方法。那么dp[i] [j] 的递推表达式是:

dp[i] [j] = dp[i-1] [j] + dp[i] [j-1]

3. 实现

class Solution(object):
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        dp  = [ [ 1 for i in range(n+1)] for j in range(m+1) ] 
        for i in range( 1 , m+1) :
            for j in range( 1 , n +1  ):
                dp[i][j] = dp[i-1][j] + dp[i][j-1]
        return dp[m-1][n-1]
posted @ 2019-05-26 14:40  bush2582  阅读(63)  评论(0编辑  收藏  举报