繁体   English   中英

将数组添加到数组列表为空

[英]adding arrays to a list of arrays is blank

因此,我正在编写一种方法来递归查找数字列表的所有排列。

我将每次运行的结果(即数字数组)添加到更大的combos数组中。 但是,组合变得像这样用空数组填充: [[],[],[]]代替[[1,2,3],[3,2,1],[2,3,1] ...]但我知道组合正在生成

这是我所拥有的:

var combos = [];
permuteHelper([1,2,3],[]);
console.log(combos); //printing blank array or arrays [[],[]]
function permuteHelper(list, combination){

    if(list.length == 0){
        combos.push(combination); //ERROR: combos only holds blank arrays (e.g. [[],[]] )
        console.log(combination); //although this is printing correct list after each recursive run (e.g. [3,2,1] )
    }
    for(var i = 0; i < list.length; i++ ){

        //pick a digit
        var digit = list[i];
        list.splice(i,1); //remove the character from the array
        combination.push(digit);

        //recursively keep picking
        permuteHelper(list, combination);

        //backtrack and put the digit back for next time
        list.splice(i,0,digit);
        combination.pop();
    }

}

我尝试使组合成为非全局的并且更新了函数头

function permuteHelper(list, combination,combos)

但是组合仍然无法正确填充。 我是JS新手,不确定我缺少什么。

当您将combination作为函数的参数时,它将被视为参考。 combination任何更改都会更改原始变量。 您将该引用permuteHelperpermuteHelper每个新调用,因此始终修改原始数组。

只需进行少量代码更改的原始解决方案是:

var combos = [];
permuteHelper([1, 2, 3], [], []);

function permuteHelper(list, _combination) {
    var combination = Object.assign([], _combination);
    if (list.length == 0) {
        combos.push(combination); //this only has a blank array of 
        arrays(e.g. [[], []])
        console.log(combination); //prints correct permuted list after each recursive trial (e.g. [3,2,1] )
    }
    for (var i = 0; i < list.length; i++) {

        //pick a digit
        var digit = list[i];
        list.splice(i, 1); //remove the character from the array
        combination.push(digit);

        //recursively keep picking
        permuteHelper(list, combination, combos);

        //backtrack and put the digit back for next time
        list.splice(i, 0, digit);
        combination.pop();
    }
}

这样,您可以根据参数_combination创建一个新的对象combination ,可以根据需要对其进行修改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM