描述:
使用了递归,有些计算是重复的,用了额外的空间,Version 1是m*n
Bonus:一共走了m+n步,例如 m = 2, n = 3 [#, @, @, #, @],所以抽象成数学问题,解是C(m + n, m)
代码:
1 class Solution: 2 # @return an integer 3 def __init__(self): 4 self.record = {} 5 6 def uniquePaths(self, m, n): 7 if m == 0 or n == 0: return 0 8 if m == 1 or n == 1: return 1 9 10 if (m-1, n) in self.record: 11 a = self.record[(m-1, n)] 12 else: 13 a = self.uniquePaths(m-1, n) 14 self.record[(m-1, n)] = a 15 16 if (m, n-1) in self.record: 17 b = self.record[(m, n-1)] 18 else: 19 b = self.uniquePaths(m, n-1) 20 self.record[(m, n-1)] = b 21 22 return a + b 23 24 foo = Solution() 25 print foo.uniquePaths(1, 2)
#Leet Code# Unique Path
时间: 2024-10-21 06:32:04