0

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..

1 Answers1

0

When you call:

  return result.push(solution);

You're still using the same Array object again, any later change to that object will be persisted on the result. You need to make a clone of the solution object each time you push it to result:

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

Here is the new Fiddle: Fiddle.

Giang Le
  • 94
  • 5