Unique Paths - LeetCode

来源:互联网 发布:windows刻录光盘 编辑:程序博客网 时间:2024/06/06 17:38

Unique Paths - LeetCode

题目:

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?


分析:

这是一道动态规划的题目,我们试想,在grid[a][b]这一块时,我们只能从grid[a][b-1]和grid[a-1][b]到这一块,而从第一块能到这一块的方法总共有多少呢?等于到grid[a][b-1]和grid[a-1][b]的方法数相加。而当一直推到a = 2 和 b=2 时,我们到grid[a][b]的方法 = grid[a][b-1]和grid[a-1][b] , 即grid[2][1]和grid[1][2],而这两个都等于1。看懂这个过程,接下来我们就可以写代码了。

代码:

class Solution:    # @return an integer    def uniquePaths(self, m, n):        table =[[1 for i in range(n)] for j in range(m)]        for i in range(1,m):            for j in range(1,n):                table[i][j] = table[i-1][j]+table[i][j-1]        return table[m-1][n-1]


0 0
原创粉丝点击