How to think in recursive way?

前端 未结 7 1099
逝去的感伤
逝去的感伤 2021-01-30 19:02

In order to understand the advanced algorithm concepts like greedy methods and dynamic programming, one first need to be well versed in recursion.

I am relatively new to

7条回答
  •  长情又很酷
    2021-01-30 19:31

    Let's take a simple task. Printing numbers from 1 to 10. I'll use Python2.7 here.

    for i in range(1,11):
        print i
    

    Now let's try to do the same, using recursion.

    >>> def print_me(n):
        if n > 0:
            print_me(n - 1)
            print n
        else:
            return
    
    >>> print_me(10)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    

    So how do we think of it ?

    • Step1: Think of my boundaries. I need two . 1 and 10. Next.
    • Step2: The print statement. That's our motive. To print numbers. And we want it from 1 to 10. So I need to print 1 first.
    • Step3: We start by writing a function that does the job of printing a number passed as an argument. Let's think of just, the main task.

      def print_me(n): print n

    • Step 4: I want the function to return, if n < 1.

      def print_me(n): if n > 0: print n else: return

    • Step 5: Now I want to pass numbers, from 1 to 10 to this function, but we don't want a loop of 1 to 10 , and then pass it to our function. We want it to be done recursively.

    What is recursion? In plain words, the repeated application of a recursive procedure or definition.

    So in order to make it recursive, we need to call the function itself. And we want to pass our range of 1 to 10.

    def print_me(n):
        if n > 0:
            print_me(n - 1)
            print n
        else:
            return
    

    Summarizing: All recursive calls must obey 3 important rules:

    1. A recursive algorithm, MUST have a base case.
    2. A recursive algorithm, MUST change its state and move toward the base case.
    3. A recursive algorithm MUST call itself, recursively.

    Source : interactivepython

    Another program in Javascript to find factorial:

    function factorial(n){
        if (n == 1)
            {
            return 1;
            }
        else {
            return n * factorial(n-1);
            }
    }
    

提交回复
热议问题