LeetCode - 为什么这个函数 return 未定义,尽管它刚刚记录了一个数组?

LeetCode - Why does this function return undefined, although it has just logged an array?

由于我是编程新手,我目前正在尝试通过解决 LeetCode 上的一些简单问题来应用我学到的基础知识。然而,“3Sum”问题让我遇到了一些我似乎不明白的事情。 这是练习的定义:

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

现在,这是我已经想到的:

var result = [];
var threeSum = function(nums) {
    for (let i = 1; i < nums.length; i++) {
        for (let j = i + 1; j < nums.length; j++) {
            if (nums[0] + nums[i] + nums[j] == 0) {
                result.push([nums[0], nums[i], nums[j]])
            }
        }
    }

    if(nums.length > 3) {
        nums.shift();
        threeSum(nums);
    } else {
        console.log("result: ", result);
        return result;
    } 
};

现在我正在使用以下输入对此进行测试:

[-1,0,1,2,-1,-4]

底部 else 块中的 console.log 语句给出:

result: [ [ -1, 0, 1 ], [ -1, 2, -1 ], [ 0, 1, -1 ] ]

这正是我希望它现在注销的内容。

然而 return 下面的语句 returns "undefined".

因为它们都在同一个else 块中,所以我认为它们都应该被执行。 "result" 如何记录为数组,但是 return 导致它成为 "undefined"?

请注意,我知道这可能不是解决此问题的正确方法,而且这个解决方案也不足以完成练习。我不要求任何更正,因为我想自己开发算法,只是事实是,在这种情况下,"result" 似乎同时被定义和未定义:)

你快到了。只需添加 return 即可进行递归:

var result = [];
var threeSum = function(nums) {
    for (let i = 1; i < nums.length; i++) {
        for (let j = i + 1; j < nums.length; j++) {
            if (nums[0] + nums[i] + nums[j] == 0) {
                result.push([nums[0], nums[i], nums[j]])
            }
        }
    }

    if(nums.length > 3) {
        nums.shift();
        return threeSum(nums);  // <-- return here
    } else {
        return result;
    } 
};

console.log(threeSum([-1,0,1,2,-1,-4]))