A permutations problem (LeetCode), which finds the permutations of an array [1,2,3], is returning an empty array through a backtracking recursive function. The console prints out the following:
Input
nums =
[1,2,3]
Stdout
[ [ 1, 2, 3 ] ]
[ [ 1, 3, 2 ] ]
[ [ 2, 1, 3 ] ]
[ [ 2, 3, 1 ] ]
[ [ 3, 1, 2 ] ]
[ [ 3, 2, 1 ] ]
Output
[[]]
This would be the proper solution if the array didn't seem to be re-instantiated on every recursive call.
Here is the code:
/**
* @param {number[]} nums
* @return {number[][]}
*/
var permute = function(nums) {
let s = [], a = [];
return findPerm(nums, s, a);
};
var findPerm = function(nums, stack, ans){
if(nums.length === stack.length){
if(ans.indexOf(stack) === -1)
ans.push(stack);
console.log(ans);
}
for(let num of nums){
if(stack.indexOf(num) === -1){
stack.push(num);
findPerm(nums, stack, ans);
stack.pop();
}
}
return ans;
};
permute([1,2,3]);
Why am I getting an empty array returned?
This happens because you're pushing stack
to ans
, but then also modifying that same stack
array reference later on with stack.pop()
, making the array pushed appear empty. One way to fix this would be to make a copy of the stack
array when you push it into ans
:
ans.push(stack.slice());
now when you .pop()
, it won't modify this new array reference anymore.
const permute = function(nums) {
const s = [], a = [];
return findPerm(nums, s, a);
};
const findPerm = function(nums, stack, ans) {
if (nums.length === stack.length) {
ans.push(stack.slice());
}
for (let num of nums) {
if (stack.indexOf(num) === -1) {
stack.push(num);
findPerm(nums, stack, ans);
stack.pop();
}
}
return ans;
};
console.log(permute([1, 2, 3]));