我有一段JavaScript代码两次调用了递归方法,结果无法传回:
var subSum = (nums, target) => {
var res = [];
var chosen = [];
subSets(nums, chosen, target, res);
return res;
};
var subSets = (nums, chosen, target, res) => {
if (nums.length === 0) {
if (sumAry(chosen) == target) {
console.log(array2Str(chosen));
res.push(chosen);
}
//console.log(array2Str(chosen));
} else {
let it = nums[0];
nums.shift();
chosen.push(it);
subSets(nums, chosen, target, res);
chosen.pop();
subSets(nums, chosen, target, res);
nums.unshift(it);
}
};
var array2Str = (ary) => {
if (!ary || ary.length < 1) return '';
let res = [];
arrayToStr(ary, res);
return res.join("");
};
var arrayToStr = (ary, res) => {
res.push('[');
for(let i = 0; i < ary.length; i ++) {
let it = ary[i];
if (Array.isArray(it)) {
arrayToStr(it, res);
if (i != ary.length - 1) {
res.push(', ');
}
} else {
res.push( (i == ary.length - 1) ? `${it}` : `${it}, `);
}
}
res.push(']');
};
测试代码为:
let nums = [5,3,1,2,4,6];
console.log(`array2Str(subSum(nums, 7))`);
输出为:
Debugger attached.
[5, 2]
[3, 4]
[1, 2, 4]
[1, 6]
[[], [], [], []]
您可以看到最后一行是结果数组(res)的转储,并且4个子数组的内容为空,但是根据上面的控制台日志,这些值已被推入结果数组。无论如何,如果我注释掉最后一个subSets递归调用,则最终结果打印不会为空。 关于如何通过两次递归调用传回结果的任何想法?我尝试了一个全局数组容器,但没有一个。
答案 0 :(得分:0)
该数组通过引用传递,也就是说正在被覆盖。 使用诸如字符串之类的原始类型,或使用选定的数组的浅表副本。
为此,将推送线更改为此
res.push(chosen.slice()) // for shllow copy
res.push(chosen.join()) // for using primitive string
// i assume that the missing sumAry function shuld do ..
const sumAry = array => array.reduce((a, b) => a + b, 0)
var subSum = (nums, target) => {
var res = []
var chosen = []
subSets(nums, chosen, target, res)
return res
}
var subSets = (nums, chosen, target, res) => {
if (nums.length === 0) {
if (sumAry(chosen) == target) {
console.log(array2Str(chosen))
res.push(chosen.slice())
// res.push(chosen.join())
}
} else {
let it = nums[0]
nums.shift()
chosen.push(it)
subSets(nums, chosen, target, res)
chosen.pop()
subSets(nums, chosen, target, res)
nums.unshift(it)
}
}
var array2Str = ary => {
if (!ary || ary.length < 1) return ''
let res = []
arrayToStr(ary, res)
return res.join('')
}
var arrayToStr = (ary, res) => {
res.push('[')
for (let i = 0; i < ary.length; i++) {
let it = ary[i]
if (Array.isArray(it)) {
arrayToStr(it, res)
if (i != ary.length - 1) {
res.push(', ')
}
} else {
res.push(i == ary.length - 1 ? `${it}` : `${it}, `)
}
}
res.push(']')
}
let nums = [5, 3, 1, 2, 4, 6]
console.log(array2Str(subSum(nums, 7)))