14年11月份的时候 用cpp在POJ上面刷了10来题
15年7月份用python 刷leetcode刷了10来题
现在15年12月份又开始刷leetcode,还是用python,目前已经挑比较容易的完成了 45 道
记录下 值得复习的题目 198. House Robber
这题172. Factorial Trailing Zeroes 分析出问题本质后,这性能飞速的阿
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
'''
fac = reduce(lambda x, y: x*y, xrange(1, n+1))
a = 10
b = 0
while True:
if fac % a == 0:
a *= 10
b += 1
else:
break
return b
'''
a, b = divmod(n, 5)
s = a
while a >= 5:
a, b = divmod(a, 5)
s += a
return s
题目112 path sum 用搜索的方法,DFS,好久前写过,但这种东西很容易忘。这次没看其他资料,完全自己写了一遍,调了一下,希望能彻底掌握
记下要点吧,
1 要有DFS子函数,还要有一个记录已访问过节点全局变量,
2 DFS函数的开头设置停止的条件,抛出True或False,
3 访问该节点的联通节点,即递归调用dfs函数, 并对返回结果进行处理,比如 if dfs(): return true 使结果不断抛出,如果是false就记录该节点,
4 最后在记录访问相邻节点后的该节点
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
def dfs(root, sum):
if root.left == None and root.right == None:
if root.val == sum:
return True
else:
return False
if root.left != None:
if d.get(root.left, -1) == -1:
if dfs(root.left, sum-root.val):
return True
d[root.left] = sum-root.val
if root.right != None:
if d.get(root.right, -1) == -1:
if dfs(root.right, sum-root.val):
return True
d[root.right] = sum -root.val
d[root] = sum
return False
if root == None:
return False
d = {}
d[root] = sum
return dfs(root, sum)