什么是递归,它是如何工作的? [英] What is recursion and how does it work?

查看:57
本文介绍了什么是递归,它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下递归到底是什么(以及它在 Ruby 中是如何工作的,如果这要求不高的话).我遇到了一个依赖递归的冗长代码片段,这让我很困惑(我现在弄丢了,它并不完全相关).

Could someone please explain what exactly recursion is (and how it works in Ruby, if that's not too much to ask for). I came across a lengthy code snippet relying on recursion and it confused me (I lost it now, and it's not entirely relevant).

推荐答案

递归函数/方法调用自身.要终止递归算法,您需要一个基本情况(例如,函数递归调用自身的条件),并且您还需要确保在每次递归调用中都更接近该基本情况.我们来看一个非常简单的例子:

A recursive function/method calls itself. For a recursive algorithm to terminate you need a base case (e.g. a condition where the function does not call itself recursively) and you also need to make sure that you get closer to that base case in each recursive call. Let's look at a very simple example:

def countdown(n)
  return if n.zero? # base case
  puts n
  countdown(n-1)    # getting closer to base case 
end               

countdown(5)
5
4
3
2
1

有些问题可以用递归来非常优雅地表达,例如,很多数学函数都是用递归的方式描述的.

Some problems can be very elegantly expressed with recursion, e.g a lot of mathematical functions are described in a recursive way.

这篇关于什么是递归,它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆