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;
    }
};
相关推荐
Navigator_Z12 小时前
LeetCode //C - 1278. Palindrome Partitioning III
c语言·算法·leetcode
青山木15 小时前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
All for pursuit.18 小时前
【回溯-4】46.全排列
数据结构·c++·算法·leetcode
All for pursuit.21 小时前
【回溯-5】78.子集
数据结构·c++·算法·leetcode
代码什么用1 天前
LeetCode-560.和为 K 的子数组
算法·leetcode
All for pursuit.1 天前
【回溯-3】39.组合总和
数据结构·c++·算法·leetcode
yi0111 天前
DAY19: LeetCode 28 找出字符串中第一个匹配项的下标
人工智能·笔记·python·算法·leetcode
不会就选b1 天前
算法日常・每日刷题--<动态规划>6
数据结构·算法·leetcode
0+1112 天前
算法 --模拟
c++·算法·leetcode
Nil2082 天前
leetcode 739每日温度
算法·leetcode·职场和发展