递归(Recursion)

一、递归

递归:通过函数体来进行的循环

汇编:它没有所谓的循环嵌套这一说,你之前有一段指令写在什么地方,你不断的跳到之前的指令的地方去执行那条指令,这就是递归。

  1. 从前有个山
  2. 山里有个庙
  3. 庙里有个和尚讲故事
  4. 返回1

二、盗梦空间

  • 向下进入不通梦境中;向上又回到原来一层
  • 通过声音同步回到上一层
  • 每一层的环境和周围的人都是一份拷贝、主角等几个人穿越不通的梦境(发生和携带变化)

计算 n!

n! = 1 * 2 * 3 * ... * n

def Factorial(n):
    if n <= 1 :
        return 1
    return n * Factorial(n - 1)

三、递归-代码模板

  1. 终结条件(terminator)
  2. 处理当前层逻辑(current level logic)
  3. 下探到下一层(drill down)
  4. 清理当前层(reverse)

C/C++模版:

void recursion(int level, int param) { 
  // recursion terminator
  if (level > MAX_LEVEL) { // 一、递归终结条件
    // process result 
    return ; 
  }

  // process current logic 
  process(level, param);  // 二、处理当前层逻辑

  // drill down 
  recursion(level + 1, param);// 三、下探到下一层

  // reverse the current level status if needed // 四、清理当前层
}

Java模版:

// Java
public void recur(int level, int param) { 
    // terminator 
    if (level > MAX_LEVEL) { 
        // process result 
        return; 
    }
    // process current logic 
    process(level, param); 
    // drill down 
    recur(level: level + 1, newParam); 
    // restore current status 
}  

Python模版:

def recursion(level, param1, param2, ...): 
    # recursion terminator 
    if level > MAX_LEVEL: 
   process_result 
   return 
    # process logic in current level 
    process(level, data...) 
    # drill down 
    self.recursion(level + 1, p1, ...) 
    # reverse the current level status if needed
    

JavaScript 模版:

const recursion = (level, params) =>{
   // recursion terminator
   if(level > MAX_LEVEL){
     process_result
     return 
   }
   // process current level
   process(level, params)
   //drill down
   recursion(level+1, params)
   //clean current level status if needed
   
}

四、思维要点

  1. 不要人肉进行递归(最大误区) 刚开始学,可以把状态树画出来。到后面了直接看函数本身开始写即可。
  2. 找到最近最简方法,将其拆解成可重复解决的问题(重复子问题)
  3. 数学归纳法思维。

五、LeetCode 题目

https://leetcode-cn.com/problems/climbing-stairs/

https://leetcode-cn.com/problems/generate-parentheses/

https://leetcode-cn.com/problems/invert-binary-tree/description/

https://leetcode-cn.com/problems/validate-binary-search-tree

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree

https://leetcode-cn.com/problems/minimum-depth-of-binary-tree

https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/

https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/

https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal

https://leetcode-cn.com/problems/combinations/

https://leetcode-cn.com/problems/permutations/

https://leetcode-cn.com/problems/permutations-ii/

  • 16
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值