leetcode 18. 四数之和

题目描述

leetcode 15. 三数之和用同样的方法。有两个注意点。

一是剪枝的逻辑

这是和15. 三数之和 - 力扣(LeetCode)问题不同的地方。

无法通过这种情况:

二是整数溢出

最终答案

cpp 复制代码
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        int len = nums.size();
        int left = 0;
        int right = 0;
        vector<vector<int>> res;
        for(int i = 0;i <len;i++){
            if(nums[i]>0 && nums[i]>=target)
                break;
            if(i>0&&nums[i-1]==nums[i])
                continue;
            for(int j=i+1;j <len;j++){
                if(nums[j]>0 && nums[i]+nums[j] >= target)
                    break;
                if(j>i+1 && nums[j-1]==nums[j])
                    continue;
                left=j+1;
                right=len-1;
                while(left<right){
                    if((long)nums[i]+nums[j]+nums[left]+nums[right] == target){
                        res.push_back({nums[i],nums[j],nums[left],nums[right]});
                        while(left<right-1&&nums[left]==nums[left+1]) left++;
                        while(left<right-1&&nums[right]==nums[right-1]) right--;
                        left++;
                        right--;
                    }
                    else if((long)nums[i]+nums[j]+nums[left]+nums[right] > target){
                        right--;
                    }else{
                        left++;
                    }
                }
            }
        }
        return res;
    }
};
相关推荐
YGGP4 小时前
【Golang】LeetCode 128. 最长连续序列
leetcode
月挽清风12 小时前
代码随想录第十五天
数据结构·算法·leetcode
TracyCoder12314 小时前
LeetCode Hot100(34/100)——98. 验证二叉搜索树
算法·leetcode
We་ct15 小时前
LeetCode 56. 合并区间:区间重叠问题的核心解法与代码解析
前端·算法·leetcode·typescript
努力学算法的蒟蒻18 小时前
day79(2.7)——leetcode面试经典150
算法·leetcode·职场和发展
2401_8414956418 小时前
【LeetCode刷题】二叉树的层序遍历
数据结构·python·算法·leetcode·二叉树··队列
2401_8414956419 小时前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
我是咸鱼不闲呀19 小时前
力扣Hot100系列19(Java)——[动态规划]总结(上)(爬楼梯,杨辉三角,打家劫舍,完全平方数,零钱兑换)
java·leetcode·动态规划
铉铉这波能秀20 小时前
LeetCode Hot100数据结构背景知识之列表(List)Python2026新版
数据结构·leetcode·list
仟濹20 小时前
算法打卡 day1 (2026-02-06 周四) | 算法: DFS | 1_卡码网98 可达路径 | 2_力扣797_所有可能的路径
算法·leetcode·深度优先