How to think in recursive way?

前端 未结 7 1235
逝去的感伤
逝去的感伤 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:28

    There is a way of thinking about recursion that makes it as easy as iteration.

    In iteration we have a loop. Think of it as having 4 parts:

    1. A decision to continue or stop, based on some "controlling" data, evaluated as a logical condition.

    2. A body, where the work is done. Sometimes, the body is combined with the next part.

    3. A way of changing the "controlling" data. Often by changing a counter.

    4. A way of invoking the construct (in this case, the loop) again. In c-style languages this is provided by the for, while, or do syntax.

    In recursion we have a function (sometimes several). They have the same 4 parts:

    1. A decision to continue or stop, based on some "controlling" data, evaluated as a logical condition. The controlling data is usually passed to the function as parameter(s).

    2. A body, where the work is done. Sometimes, the body is combined with the next part.

    3. A way of changing the "controlling" data. Often by changing a counter.

    4. A way of invoking the construct (in this case, the function) again - that means call the function (and remember to pass the changed "controlling" data.

    It should be of no surprise that the two constructs have the same parts, since they are equivalent.

提交回复
热议问题