美文网首页
Algorithm-Preparation: Recursion

Algorithm-Preparation: Recursion

作者: yingshaoxo | 来源:发表于2017-06-22 17:36 被阅读30次

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.

相关文章

  • Algorithm-Preparation: Recursion

    Suppose you're digging through your grandma's attic and c...

  • Binary Tree and Recursion

    DFS Non-recursion (use stack) Recursion (自己调用自己)-- Traver...

  • Recursion

    How to calculate the complexity? How about the space?

  • Recursion

    Fibonacci Find the maximum value among array elements Bub...

  • Recursion

    发自简书 递归 导致递归的方法返回而没有再一次进行递归调用,此时我们称为基值情况( base case)。每一个递...

  • Recursion

    有限记忆和无限思维之间的矛盾促生了语言的递归性 语言是用有限手段生成无限话语的装置.如果一种语法没有递归机制,它将...

  • Recursion

    Fibonacci A frog can jump one or two steps at a time. How...

  • recursion

    22 Generate Parentheses 39 Combination Sum 40 Combination...

  • Algorithm-Preparation: Arrays an

    Sometimes you need to store a list of elements in memory....

  • 递归

    recursion完成了iteration,但逻辑清晰,有以下问题: recursion 由stack完成,会溢出...

网友评论

      本文标题:Algorithm-Preparation: Recursion

      本文链接:https://www.haomeiwen.com/subject/gvjjqxtx.html