See the fiddle here JSFIDDLE
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;
};
var b = combine(4, 2);
console.log(b);
why the result array always contain the same element>I mean it should have the same value like the array solution?
b 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]]
I expected this:
[[2, 1], [3, 1], [4, 1], [1, 2], [3, 2], [4, 2], [1, 3], [2, 3], [4, 3], [1, 4], [2, 4], [3, 4]]
I guess it's a closure problem .but how could I do this???
I try to make the result[]
as a global var.but still not work..
I see that post. but it's closure within a loop. but this is not caused by loop problem .loop actually works fine.It's a recursive problem within a closure..