美文网首页
Q62 Unique Paths

Q62 Unique Paths

作者: 牛奶芝麻 | 来源:发表于2018-10-20 00:29 被阅读31次
进阶版本(有障碍的路径):

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:
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:
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 实现:
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

相关文章

网友评论

      本文标题:Q62 Unique Paths

      本文链接:https://www.haomeiwen.com/subject/lvlpzftx.html