leetcode 做题记录

博主分享了自己使用Python在LeetCode上刷题的经历,从14年到15年的不同阶段,目前重点是刷较易题目,并记录了值得复习的题目如198. House Robber和172. Factorial Trailing Zeroes。针对题目112. Path Sum,博主通过深度优先搜索(DFS)重新实现,强调了DFS子函数、全局已访问节点变量、停止条件及如何处理递归返回结果等关键点。

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)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值