How does this recursion work?
Solution 1:
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!
Solution 2:
You just have to create the tree of invocations to figure this out:
findSequence(24)
find(1, "1")
find(1 + 5, "(1 + 5)")
find(6 + 5, "((1 + 5) + 5)")
find(11 + 5, "(((1 + 5) + 5) + 5)"
find(16 + 5, "((((1 + 5) + 5) + 5) + 5)"
find(21 + 5, "(((((1 + 5) + 5) + 5) + 5) + 5)"
start > goal: return null
find(21 * 3, "(((((1 + 5) + 5) + 5) + 5) + 5)"
start > goal: return null
find(16 * 3, "((((1 + 5) + 5) + 5) * 3)"
start > goal: return null
find(11 * 3, "(((1 + 5) + 5) * 3)"
start > goal: return null
find(6 * 3, "((1 + 5) * 3)")
find(18 + 5, "(((1 + 5) * 3) + 5)")
find(23 + 5, "((((1 + 5) * 3) + 5) + 5)")
start > goal: return null
find(23 * 3, "((((1 + 5) * 3) + 5) * 3)")
start > goal: return null
find(18 * 3, "(((1 + 5) * 3) * 3)")
start > goal: return null
find(1 * 3, "(1 * 3)")
find(3 + 5, "((1 * 3) + 5)")
find(8 + 5, "(((1 * 3) + 5) + 5)")
find(13 + 5, "((((1 * 3) + 5) + 5) + 5)")
find(18 + 5, "(((((1 * 3) + 5) + 5) + 5) + 5)")
find(23 + 5, "((((((1 * 3) + 5) + 5) + 5) + 5) + 5)")
start > goal: return null
find(23 + 5, "((((((1 * 3) + 5) + 5) + 5) + 5) + 5)")
start > goal: return null
find(18 * 3, "(((((1 * 3) + 5) + 5) + 5) * 3)")
start > goal: return null
find(13 * 3, "((((1 * 3) + 5) + 5) * 3)")
start > goal: return null
find(8 * 3, "(((1 * 3) + 5) * 3)")
return "(((1 * 3) + 5) * 3)"
find(3 * 3, "((1 * 3) * 3)")
find(9 + 5, "(((1 * 3) * 3) + 5)")
find(14 + 5, "((((1 * 3) * 3) + 5) + 5)")
find(19 + 5, "(((((1 * 3) * 3) + 5) +5) + 5)")
return "(((((1 * 3) * 3) + 5) +5) + 5)"
find(19 * 3, "((((1 * 3) * 3) + 5) *3)")
start > goal: return null
find(9 * 3, "(((1 * 3) * 3) * 3)")
start > goal: return null