How does this recursion work?

前端 未结 11 586
轮回少年
轮回少年 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条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 11:31

    The function runs a rather simple brute force search with backtracking: at each invocation level it tries adding 5 to the number, and see if starting from the resultant number gets you to the goal. If it does, the result is returned; otherwise, the number is multiplied by 3, and the search for the goal continues from that new number. As the recursion goes along, the textual representation of the expression producing the number is passed to the next invocation levels.

    The search for 14 goes as follows:

    (1,  "1")
    (5,  "1+5")
    (10, "(1+5)+5")
    (15, "((1+5)+5)+5") <<= Fail
    (30, "((1+5)+5)*3") <<= Fail
    (15, "(1+5)*3") <<= Fail
    (3,  "1*3")
    (8,  "(1*3)+5")
    (13, "((1*3)+5)+5")
    (18, "(((1*3)+5)+5)+5") <<= Fail
    (39, "(((1*3)+5)+5)*3") <<= Fail
    (24,  "((1*3)+5)*3") <<= Fail
    (9, "(1*3)*3")
    (14, "((1*3)*3)+5) <<= Success!
    

提交回复
热议问题