前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Q62 Unique Paths

Q62 Unique Paths

作者头像
echobingo
发布2018-11-07 15:11:31
3840
发布2018-11-07 15:11:31
举报
文章被收录于专栏:Bingo的深度学习杂货店
进阶版本(有障碍的路径):

Q63 Unique Paths II

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 7 x 3 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

Example 1:
代码语言:javascript
复制
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways 
to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
代码语言:javascript
复制
Input: m = 7, n = 3
Output: 28
解题思路:
  1. 此题画个图,明显可以用动态规划求解。刚开始,dp[n][m] 初始化为1,而 dp[n][m] = dp[n][m-1] + dp[n-1][m]。注意,如果 n 或 m 有一个值为 1,则结果为 1。
  2. 大神解法:这是一个计算题。机器人向右走 m-1 步,向下走 n-1 步,则总共要走 m+n-2 步。而对于向右走(或向下走)有 m-1 种(或 n-1 种)走法,因此结果为 C(n+m-2, m-1) 或者 C(n+m-2, n-1) 种。【C(n+m-2, m-1) = C(n+m-2, n-1)】

【注】C(N, M) = N! / (M! * (N-M)!)

两种方法的代码见Python实现部分。

Python 实现:
代码语言:javascript
复制
class Solution:
    # DP
    # Time: O(n^2)
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        dp = [[1 for col in range(m)] for row in range(n)]  # n行m列的数组
        if m == 1 or n == 1:
            return 1
        for i in range(1, n):
            for j in range(1, m):
                dp[i][j] = dp[i][j-1] + dp[i-1][j]
        return dp[i][j]

    # Math 
    # C(m+n-2, m-1) or C(m+n-2, n-1)
    # C(N, M) = N!/(M!*(N-M)!)
    # Time: O(n)
    def uniquePaths2(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        return self.calFactorial(m+n-2) // self.calFactorial(m-1) // self.calFactorial(n-1)

    def calFactorial(self, num):
        if num <= 1:
            return 1
        return num * self.calFactorial(num - 1)

m = 3
n = 7
print(Solution().uniquePaths(1, 1))  # 1
print(Solution().uniquePaths(m, n))  # 28
print(Solution().uniquePaths2(m, n)) # 28
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.10.20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 进阶版本(有障碍的路径):
  • Example 1:
  • Example 2:
  • 解题思路:
  • Python 实现:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档