正如 Yury 所提到的,您不需要递归(事实上,如果有一个问题的递归解决方案,那么也存在一个非递归解决方案!)。但如果你真的想要一个,这里是:
// length is the length of the expected strings
// partial is a partial solution (a string with at most length characters)
// partial is not a required parameter!
function recursivePrint(length, partial) {
partial = partial || ''; // initialize partial to the empty string if it is not provided
if (partial.length === length) { // exit condition
console.log(partial); // a solution should be printed
} else { // recursion incoming
// the next step from a partial solution is to build 2 more (partial) solutions by appending 0/1 before this one
recursivePrint(length, '0' + partial);
recursivePrint(length, '1' + partial);
}
}
recursivePrint(3); // start recursion
它经历的步骤:
''
'0'
'00'
'000' -> print
'100' -> print
'10'
'010' -> print
'110' -> print
'1'
'01'
'001' -> print
'101' -> print
'11'
'011' -> print
'111' -> print
总计:2^3 个解决方案
演示:http: //jsbin.com/oBiMiHe/1/edit
稍有改进,该recursivePrint
函数现在获得了一个回调,该回调会为每个解决方案调用。该演示使用然后记录的值构建一个数组。