递归
一看就会,一写就废~~
一个小朋友坐在第10排,他的作业本被小组长扔到了第1排,小朋友要拿回他的作业本,可以怎么办?他可以拍拍第9排小朋友,说“帮我拿第1排的本子”,而第9排的小朋友可以拍拍第8排小朋友,说“帮我拿第1排的本子”...如此下去,消息终于传到了第1排小朋友那里,于是他把本子递给第2排,第2排又递给第3排...终于,本子到手啦!这就是递归,拍拍小朋友的背可以类比函数调用,而小朋友们都记得要传消息、送本子,是因为他们有记忆力,这可以类比栈。
更严谨一些,递归蕴含的思想其实是数学归纳法:为了求解问题p(n),首先解决基础情形p(1),然后假定p(n-1)已经解决,在此基础上若p(n)得解,那所有问题均得解。九章算法
在函数内部代码中,调用这个函数本身:先递进再回归
个人觉得之所以想不到的原因就是没明白函数的功能,想太多了。。attention应该放在s1上
S1:这个函数的功能是什么,他要完成什么样的一件事,而这个,是完全由你自己来定义的。也就是说,我们先不管函数里面的代码什么,而是要先明白,你这个函数是要用来干什么。
S2: 寻找递归结束的条件,当参数为啥时,递归结束,之后直接把结果返回,请注意,这个时候我们必须能根据这个参数的值,能够直接知道函数的结果是什么。
S3:不断缩小参数的范围,缩小之后,我们可以通过一些辅助的变量或者操作,使原函数的结果不变。知乎专栏
https://zhuanlan.zhihu.com/p/137041568
二叉树的深度
爬楼梯问题
略。。