2017-10-14 49 views
0
function findSolution(target) { 
    function find(current, history) { 
     if (current == target) 
     {debugger; 
     return history; 
     } 
     else if (current > target){ 
     debugger; 
     return null; 
     } 
     else{ 
     debugger; 
     return find(current + 5, "(" + history + " + 5)") || 
       find(current * 3, "(" + history + " * 3)"); 
     } 
    } 
    debugger; 
    return find(1, "1"); 
    } 

    console.log(findSolution(13)); 

在它的工作到达后发现(33, “(((1 + 5)+ 5)* 3)”)为什么会发生这种删除从早期+5,而不是* 3,它只是叫什么名字?递归函数如何处理||运营商?

代码的工作:

find(1, "1") 
find(6, "(1 + 5)") 
    find(11, "((1 + 5) + 5)") 
    find(16, "(((1 + 5) + 5) + 5)") 
     too big 
    find(33, "(((1 + 5) + 5) * 3)") //why does this remove +5 from earlier and not *3 it just called 
     too big 
    find(18, "((1 + 5) * 3)") 
    too big 
find(3, "(1 * 3)") 
    find(8, "((1 * 3) + 5)") 
    find(13, "(((1 * 3) + 5) + 5)") 
     found! 

回答

3

find()结果在一个新的地方history每次调用。您的递归调用不需要更改history;他们创造新的弦乐。

因此,在

return find(current + 5, "(" + history + " + 5)") || 
      find(current * 3, "(" + history + " * 3)"); 

调用函数与+ 5形式第一,如果这则返回null它被称为与* 3形式。所以+ 5永远不会被“删除”;该字符串被简单地丢弃。

此外,至于||,如果左边的表达式返回非null,那么根本不计算右边。

+0

好吧,所以找到(33)返回null,但为什么它返回null前一个函数调用,而不是它刚刚调用的* 3函数? – Newbie21

+0

@ Newbie21if *这两个*函数调用在'||'的任一侧返回'null',那么整体表达式是'null'。换句话说,'find()'有两种方法可以返回'null':当'current'大于'target',并且当'current + 5'和'current * 3' *都大于' target'。 – Pointy

+0

好吧,因为'find(16)'&'find(33)'都返回null,它反过来使'find(11)'null,所以函数回滚到'find(6)'和* 3部分执行'||'以导致'find(18)'。 – Newbie21