提问人:Ankit Verma 提问时间:10/1/2022 最后编辑:Ankit Verma 更新时间:10/1/2022 访问量:60
为什么 combinationSum 函数返回的数组是空的(Javascript)?
Why the array returned by the combinationSum function is empty (Javascript)?
问:
combinationSum 函数返回的 resultArr 为空。当我控制台记录 ds 数组时,它会打印正确答案,但最终的输出数组是 [[],[]]。
var combinationSum = function(candidates, target) {
const resultArr = []
function combinationSumHelper(idx, candidates, ds, target){
if(idx === candidates.length){ // base case
if(target === 0){
console.log(ds) *// This line outputs right ans but resultArr returned by combinationSum function is empty*
resultArr.push(ds)
}
return
}
if(candidates[idx] <= target){
ds.push(candidates[idx])
combinationSumHelper(idx, candidates, ds, target - candidates[idx])
ds.pop()
}
combinationSumHelper(idx+1, candidates, ds, target)
}
combinationSumHelper(0, candidates, [], target)
return resultArr
};
console.log(combinationSum([2,3,6,7], 7))
输出: [ [], [] ]
预期输出:[[2,2,3],[7]]
标准: [ 2, 2, 3 ] [ 7 ]
答:
1赞
harryh
10/1/2022
#1
这将为您提供所需的输出:
var combinationSum = function(candidates, target) {
const resultArr = []
function combinationSumHelper(idx, candidates, ds, target){
if(idx === candidates.length){ // base case
if(target === 0){
console.log(ds) *// This line outputs right ans but resultArr returned by combinationSum function is empty*
resultArr.push([...ds])
}
return
}
if(candidates[idx] <= target){
ds.push(candidates[idx])
combinationSumHelper(idx, candidates, ds, target - candidates[idx])
ds.pop()
}
combinationSumHelper(idx+1, candidates, ds, target)
}
combinationSumHelper(0, candidates, [], target)
return resultArr
};
console.log(combinationSum([2,3,6,7], 7))
您面临的问题是下面的子句,并且正在改变您的数组和最终输出。if
ds.push
ds.pop
通过将代码更改为 ,可以创建数组的副本。这将确保它不会进一步变异。resultArr.push([...ds])
当我运行此代码时,我得到的输出是: [[2, 2, 3], [7]]
评论
*
console.log(ds) *