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]]
AiOtuka
9 years, 5 months ago