问题描述
我正在尝试解决此问题,我必须在数组中添加任何2个数字,并且总和应等于特定的目标数字。我已经使用循环进行了此操作,但是我决定也使用递归进行此操作。请告诉我我做错了什么?
谢谢
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function (nums,target) {
function findindices(i,j) {
const possibleTarget = nums[i] + nums[j];
if (possibleTarget === target) {
return [i,j];
} else if (j <= nums.length - 1) {
findindices(i,j + 1);
} else {
findindices(i + 1,j + 1);
}
}
return findindices(0,1); //undefined
};
解决方法
在这样的两个递归调用之前添加return
,以便将递归获得的结果返回到调用链中:
var twoSum = function (nums,target) {
function findIndices(i,j) {
const possibleTarget = nums[i] + nums[j];
if (possibleTarget === target) {
return [i,j];
} else if (j <= nums.length - 1) {
return findIndices(i,j + 1);
} else {
return findIndices(i + 1,j + 1);
}
}
return findIndices(0,1); //undefined
};