标签:oca ogre init bin leetcode ret com hat 节点
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?
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
2 * 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)
不过很遗憾,这种算法leetcode OJ跑到 37 / 62 个测试样例时就超时了。
求所有不重复路径, Unique Paths, LeetCode题解(四)
标签:oca ogre init bin leetcode ret com hat 节点
原文地址:https://www.cnblogs.com/importsober/p/13209961.html