Q:javascript 递归如何实时返回当时的值,目前返回值为递归完成后变量的值,创建闭包好像也没能达预期?



 var combine = function(n, k) {

    function backtracking(n, k) {
        if(k){  // min(k)=1, when k=0 break
            for(var i=1; i<=n; ++i){
                if(!used[i]){
                    used[i] = true;
                    solution[k-1] = i;  // solution.length=k
                    // console.log(solution.length);
                    arguments.callee(n, k-1);
                    used[i] = false;
                }
            }
        }else{
            console.log(solution);
            return result.push(solution);    // ?
        }
    }

    var used = [],
            result = [],
            solution = [];
    if(k>n){
        return [];
    }else{
        backtracking(n, k);
    }

    return result;
};

combine(4, 2);

solution output:


 [2, 1]
[3, 1]
[4, 1]
[1, 2]
[3, 2]
[4, 2]
[1, 3]
[2, 3]
[4, 3]
[1, 4]
[2, 4]
[3, 4]

result output:


 [[3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4]]

result expect:


 [[2, 1], [3, 1], [4, 1], [1, 2], [3, 2], [4, 2], [1, 3], [2, 3], [4, 3], [1, 4], [2, 4], [3, 4]]

递归 JavaScript 数组 闭包

AiOtuka 9 years, 6 months ago

引用类型 每次修改都是同一个。你需要创建一个副本,随便调用数组的一个能返回浅拷贝的方法就行了。比如楼上的slice() 或者cancat 等等

huangna answered 9 years, 6 months ago


 return result.push(solution);

改为如下即可:


 return result.push(solution.slice(0));

高町フェイト answered 9 years, 6 months ago

Your Answer