leetcode 62. Unique Paths
Posted lettuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 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?
思路: 由于题目只要求把unique path的个数求出来,而不要求把所有的unique path都逐个列出来,所以可以使用DP。由于机器人只能往右,或者往下走。所以最上面和最左边的一条边上,所有的位置unique path都是1。如图所示,最后的答案是m+n,所以可以得到L12的DP公式。
1 class Solution(object): 2 def uniquePaths(self, m, n): 3 """ 4 :type m: int 5 :type n: int 6 :rtype: int 7 """ 8 dp = [[1]*n for x in range(m)] 9 10 for i in range(1,m): 11 for j in range(1,n): 12 dp[i][j] = dp[i-1][j] + dp[i][j-1] 13 14 return dp[-1][-1]
这个DP table其实还可以简化为一个1-D array。
1 class Solution(object): 2 def uniquePaths(self, m, n): 3 """ 4 :type m: int 5 :type n: int 6 :rtype: int 7 """ 8 dp = [1]*m 9 10 for j in range(1,n): 11 for i in range(1,m): 12 dp[i] = dp[i-1] + dp[i] 13 14 return dp[-1]
以上是关于leetcode 62. Unique Paths的主要内容,如果未能解决你的问题,请参考以下文章