leetcode62. Unique Paths

题目描述(难度:Medium):

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?

Note: m and n will be at most 100.

Tags:Array,Dynamic Programming

Similar Problems: Unique PathII,Minimum Path Sum,Dungeon Game

法1:动态规划,分析:求解path的种类数量(种类数动规/棋盘类动规)
        设dp[i][j]表示从左上角到达grid[i][j]时的种类数,则dp[i][j] = dp[i-1][j]+dp[i][j-1]
        空间复杂度O(m*n),时间复杂度O(m*n)

代码实现:

class Solution(object):
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        #1.先做输入处理
        if m==0 or n==0:
            return 0
        #2.初始化,同时注意dp[0][0]的值
        dp = [ [1]*n for i in range(m) ]
        #3.dp
        for i in range(1, m):
            for j in range(1, n):
                dp[i][j] = dp[i-1][j]+dp[i][j-1]
        return dp[-1][-1]

法2:数学方法--组合问题,分析:从示例可以看出,必然要走8步,且其中有2步是向下走,剩余6步向右走;即对于m*n的网格来说,m-1次向下走,n-1次向右走,则一共要走m+n-2步,走法是C(m+n-2, m-1)
C(m, n)=m*(m-1)* ... *(m-n+2)*(m-n+1)  / n!   =  (m-n+i)/i, i从1-->n
空间复杂度O(1),时间复杂度O(n)

代码实现:

class Solution(object):
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """      
        #1.先做输入处理
        if m==0 or n==0:
            return 0
        
        def cmn(m, n):#求解组合数C(m, n),即在m个中选出n个的选择方法数
            if n==0:
                return 1

            res = 1
            for i in range(1, n+1):
                res *= m-n+i
                res /= i
            return res
            
        return cmn(m+n-2, m-1)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值