0

如果我有 3 位数字,我必须打印出 0 和 1 的组合,输出应该是这样的:

000 001 010 011 100 101 110 111

我知道这涉及到 2^n 的概念,但我尝试了许多算法和逻辑,但都没有成功

这是我到目前为止所拥有的:

void combination( number)    {
    if(number == 0) {
        printf("\n");
        return;
    }
    combination(number - 1);
    printf("0");
    combination(number - 1);
    printf("1");
}
4

2 回答 2

1

正如 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函数现在获得了一个回调,该回调会为每个解决方案调用。该演示使用然后记录的值构建一个数组。

于 2013-10-29T14:16:56.290 回答
1

您实际上不需要递归。

var print = function(num, digits) {
   var str = num.toString(2), diff = digits - str.length;
   return diff > 0 ? "0".repeat(diff) + str : str;
}, 
printAll = function(digits) {
   var i = 0, len = Math.pow(2, digits), result = [];
   for(; i < len; i++) {
     result.push(print(i, digits));
   }
   return result;
}

console.log(printAll(3))
于 2013-10-29T14:15:10.703 回答