Algorithm-Preparation: Recursion

Suppose you're digging through your grandma's attic and come across a mysterious locked suitcase. Grandma tells you that the key for the suitcase is probably in this other box. This box contains more boxes, with more boxes inside those boxes. The is in a box somewhere. What's your algorithm to search for the key? Think of an algorithm before you read on.

Here's one approach:

  1. Make a pile of boxes to look through.
  2. Grab a box, and look through it.
  3. If you find a box, add it to the pile to look through later.
  4. If you find a key, you're done!
  5. Repeat.

Here's an alternate approach:

  1. Look through the box.
  2. If you find a box, go to step 1.
  3. If you find a key, you're done!

Which approach seems easier to you?

The first approach uses a while loop. While the pile isn't empty, grab a box and look through it:

def look_for_key(main_box):
    pile = main_box.make_a_pile_to_look_through()
    while pile is not empty:
        box = pile.grab_a_box()
        for item in box:
            if item.is_a_box():
                pile.append(item)
            elif item.is_a_key():
                return "found the key!"

The second way uses recursion. Recursion is where a function calls itself. Here's the second way in pseudo-code:

def look_for_key(box):
    for item in box:
        if item.is_a_box():
            look_for_key(item)
        elif item.is_a_key():
            return "found the key!"

Both approach accomplish the same thing, but the second approach is clearer to me. Recursion is used when it makes the solution clearer. There's no performance benefit to using recursion; in fact, loops are sometimes better for performance.

Many important algorithms use recursion, so it's important to understand the concept.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,828评论 0 23
  • 之前一直都想学习色彩搭配的奥秘!因为每次写PPT都被老板批得简直了....每次都会说:太丑了,实在太丑了……一直在...
    Muriel小王子阅读 133评论 1 2
  • 雾里的城是苍老的。 夕阳甫落,浩浩滚滚的纱幕即纷纷兮淌下,欣欣兮涌起,源源不断翻山过海,路远迢迢奔来,无端蒙得街路...
    任宁阅读 391评论 2 4
  • 风起边城,秋临南国。 漫天云卷云舒。 满园花醉,神笔画珍图。 廊榭红英串串, 回廊外,草绿门朱。 高楼里,笑声隐隐...
    繁花落尽深眸阅读 255评论 18 12
  • 尽管有两个月的缓冲期,我拖到最后一刻取了离职证明,在工作群里说了告别,几次犹豫最终还是退了群。那是我的第一份工作,...
    growingtree阅读 163评论 1 1