码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 62. Unique Paths

时间:2017-01-25 15:19:33      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:oca   tom   题目   table   img   class   答案   ret   path   

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

标签:oca   tom   题目   table   img   class   答案   ret   path   

原文地址:http://www.cnblogs.com/lettuan/p/6349425.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!