How does this recursion work?

前端 未结 11 585
轮回少年
轮回少年 2020-11-30 11:03

This is an example from Eloquent Javascript:

By starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite amount of

11条回答
  •  猫巷女王i
    2020-11-30 11:14

    Lets leave the history parameter, we'll get to it later.

    The recursion expands to all possible operations. It starts with the value 1 as start.

    1. We first check if we reached our destination: goal, if we did- return true, meaning the path we took is correct.

    2. Second, we ask- did we go over the bound (goal)? If we did, we should return false since this path can't help us.

    3. Otherwise, lets try our two possiblities (We use OR because we need at least one):

      • Call the same function, but set start to start + 5
      • Call the same function, but set start to start * 3

    The history variable keeps the steps we take. So if a function call identifies that start == goal it returns it.

提交回复
热议问题