Skip to content

18. 四数之和 ​

  • 题号:18
  • 来源:LeetCode
  • 难度:中等
  • 标签:回溯 数组
  • 语言:TypeScript
  • 解法:1 个
  • 作者:lmliheng
  • 最近更新:2026-09-27

TypeScript · O(n^4) 时间 · O(n) 空间 · 更新于 2026-09-27

回溯枚举四元组再排序去重,注释标注超时

typescript
/**
 * @difficulty medium
 * @tags 回溯,数组
 * @time O(n^4)
 * @space O(n)
 * @note 回溯枚举四元组再排序去重,注释标注超时
 * @18. 四数之和
 */

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[][]}
 */


/**
 * 
 * @回溯解法
 * 超时.
 */
function fourSum(nums: number[], target: number) {
    let res: number[][] = []
    let n = nums.length

    const backtrack = (start: number, path: number[]) => {
        if (path.length === 4) {
            if (path[0] + path[1] + path[2] + path[3] === target) {
                res.push([...path])
            }
            return
        }

        for (let i = start; i <= n; i++) {
            path.push(nums[i])
            backtrack(i + 1, path)
            path.pop()
        }
    }

    backtrack(0, [])

    // 去重
    res.map(item => item.sort((a, b) => a - b))
    res = res.filter((item, index) => {
        return res.findIndex(i => i[0] === item[0] && i[1] === item[1] && i[2] === item[2] && i[3] === item[3]) === index
    })
    return res
};

源码:ts/leetcode/18. 四数之和.ts


在 GitHub 上查看题目所在目录:lmliheng/algorithm