1. 程式人生 > 實用技巧 >求所有不重複路徑, Unique Paths, LeetCode題解(四)

求所有不重複路徑, Unique Paths, LeetCode題解(四)

A robot is located at the top-left corner of amxngrid (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?

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

Constraints:

  • 1 <= m, n <= 100
  • It's guaranteed that the answer will be less than or equal to2 * 10 ^ 9.

求所有不相同的路徑,從左上角走到右下角。走法只能是向下或者向右。

題目中給示例是3 X 2的輸入,就是兩行三列,走法共3種。

容易看出,所有的步驟可以用一個二叉樹儲存。例如

1. Right -> Right -> Down
2. Right -> Down -> Right

3. Down -> Right -> Right

畫成二叉樹就是:

所以問題轉化為構建二叉樹和統計二叉樹葉子節點個數的問題。

class Node:
    def __init__(self, left=None, right=None):
        self.left = left
        self.right = right

class Solution(object):
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        def recursive(m, n):
            root = Node()
            if m == 1 and n == 1:
                return None
            elif m > 1 and n > 1:
                root.right = recursive(m-1, n)
                root.left = recursive(m, n-1)
            elif m > 1:
                root.right = recursive(m - 1, n)
            elif n > 1:
                root.left = recursive(m, n-1)
            return root

        def count_leaves(root):
            count = 0
            if root.left is None and root.right is None:
                count += 1
            if root.left is not None:
                count += count_leaves(root.left)
            if root.right is not None:
                count += count_leaves(root.right)
            return count
        root = recursive(m, n)
        if not root:
            return 1
        return count_leaves(root)


a = Solution()
b = a.uniquePaths(1, 1)
print(b)