首页 > 编程语言 > 详细

62. Unique Path Leetcode Python

时间:2015-01-30 16:04:36      阅读:262      评论:0      收藏:0      [点我收藏+]
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?




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

这题有两种解法

1.直接的数学表达式  choose m-1 from m+n-2

class Solution:
    # @return an integer
    def fac(self,n):
        if n==1 or n==0:
            return 1
        return n*self.fac(n-1)
    def uniquePaths(self, m, n):
        if m==1 or n==1:
            return 1
        val1=self.fac(m+n-2)
        val2=self.fac(m-1)
        val3=self.fac(n-1)
        result=val1/(val2*val3)
        return result
     


2.动态规划,每一步都是相邻最近的格子的和。 

代码如下

class Solution:
    # @return an integer
    def uniquePaths(self, m, n):
        dp=[[0 for index in range(n)] for index in range(m)]
        for row in range(m):
            dp[row][0]=1
        for col in range(n):
            dp[0][col]=1
        for row in range(1,m):
            for col in range(1,n):
                dp[row][col]=dp[row-1][col]+dp[row][col-1]
        return dp[m-1][n-1]
        


62. Unique Path Leetcode Python

原文:http://blog.csdn.net/hyperbolechi/article/details/43305383

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!