JavaScript递归函数调用覆盖

时间:2017-01-09 10:20:36

标签: javascript recursion permutation

我有一个功能:

function brackets(openStock, closeStock, s) {
  if (openStock == 0 && closeStock == 0) {
     document.getElementById('demo').innerHTML = s;
  }

  if (openStock > 0) {
     brackets(openStock - 1, closeStock + 1, s + "(");
  }
  if (closeStock > 0) {
     brackets(openStock, closeStock - 1, s + ")");
  }
}

它应该将括号内的组合写入一个段落' demo'在写完第一个之后,其他的没有写入段落。因为它是一个递归函数,我不知道如何一个接一个地连接结果(组合)。

1 个答案:

答案 0 :(得分:-1)

function brackets(openStock, closeStock,s) 
{
    if (openStock == 0 && closeStock == 0) {
       var e = document.createElement('div');
       e.innerHTML = s;

       while(e.firstChild) {
          document.getElementById('demo').appendChild(e.firstChild);
       }
    }

    if (openStock > 0) {
        brackets(openStock-1, closeStock+1, s + "(");
    }
    if (closeStock > 0) {
        brackets(openStock, closeStock-1, s + ")");
    }
}