码迷,mamicode.com
首页 > 编程语言 > 详细

62. Unique Path Leetcode Python

时间:2015-01-30 16:05:00      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:leetcode   python   dp   

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

标签:leetcode   python   dp   

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

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