zoukankan      html  css  js  c++  java
  • 递归的简单运用

    递归最核心的思想是:每一次递归,整体问题都要比原来减小,并且递归到一定层次时,要能直接给出结果!

    1.高斯求和问题,1+2+3+4+…+99+100,

    def sum_number(n):
        if n <= 0:
            return 0
        return n+sum_number(n-1)
    
    sum_number(100)

    2.评论楼的递归写法

    如果有这么一个树形结构的评论系统(博主的博客评论系统):
    
    1--直接对文章的评论
        1.1--对评论1的回复
            1.1.1--对评论1.1的回复
            1.1.2--对评论1.1的回复
            1.1.3--对评论1.1的回复
        1.2 --对评论1的回复
            1.2.1--对评论1.2的回复
        1.3 --对评论1的回复   
    2--直接对文章的评论
        2.1 --对评论2的回复
            2.1.1--对评论2.1的回复
        2.2 --对评论2的回复
    3--直接对文章的评论
    4--直接对文章的评论

    现在的要求是,将所有的评论,根据评论的关系,放入一个列表内,然后逐一打印出来

    lis = []
    all_top_comments = ["顶级评论1","顶级评论2","顶级评论3","....."]
    
    def get_comment(comments):
    
        for comment in comments:
            lis.append(comment)
            child_comments = comment.child() # 假设有一个child方法获取当前评论的所有子评论。
            if len(child_comments) > 0:  # 如果有子评论的话,就递归查找下去,否则回退
                get_comment(child_comments)
    
    get_comment(all_top_comments)
  • 相关阅读:
    《P3953 [NOIP2017 提高组] 逛公园》
    《P4180 [BJWC2010]严格次小生成树》
    《济南icpc补题》
    《levil的因子和》
    《洛谷P2704 [NOI2001]炮兵阵地》
    《Codeforces Round #689 (Div. 2, based on Zed Code Competition)》
    《2174: Leapin' Lizards》
    《3820: Revenge of Fibonacci 》
    马拉车求最长回文子串
    二分训练
  • 原文地址:https://www.cnblogs.com/dingyutao/p/9489191.html
Copyright © 2011-2022 走看看