【发布时间】:2021-11-24 01:13:29
【问题描述】:
我想在 Javascript 中使用回溯打印数组的所有子集,我的算法是正确的,但它给出了一些意想不到的答案。 我认为这与javascript语言有关。
// this is base function where i am calling recursive function .
function solveIt(A,B,C,D,E){
let ans = []; // this is ans array
let sub = []; // this is subset array
printAllSubset(A,0,sub,ans); // Calling the helper function
return ans; // returing anser
}
// My recursive code
function printAllSubset(nums,idx,sub,ans){
if(idx==nums.length){. // This is base condition
ans.push(sub);
return ans;
}
// include current index
sub.push(nums[idx]); // including the current index
printAllSubset(nums,idx+1,sub,ans); // recuring for all possible sub problem
// exclude current index
sub.pop(); // excluding the current index
printAllSubset(nums,idx+1,sub,ans); // recuring for all possible scenerio
}
const A=[1,2,3];
const res = solveIt(A,B,C);
console.log(res)
// output I am getting -
[
[], [], [], [],
[], [], [], []
]
// But the expected output should be -
[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
【问题讨论】:
-
您正在添加到子数组并直接将其删除,我不确定这应该如何保留其中的任何数据。
-
什么是
B、C、D和E?
标签: javascript algorithm recursion data-structures backtracking