LeetCode 18. 4Sum

本文介绍了一种解决四数之和问题的算法实现方法,该问题要求在给定整数数组中找到所有唯一四元组,使得四元组元素之和等于目标值。文章详细解释了使用双指针技巧配合排序来降低问题复杂度的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

/*
  Given an array S of n integers, are there elements a, b, c and d such that
  a + b + c +d = target ?
  Find all unique quadruplets in the array which gives the sum of target.
  Note:
  1: Elements in quadruplet(a, b, c d) must be in non-descending order (ie, a <= b <= c <= d)
  2: the solution set must not contain duplicate quadruplets.
  For example:
    Given array S = {1, 0, -1, 0, -2, 2} and target = 0;
    A solution set is {-1, 0, 0, 1} {-2, -1, 1, 2} {-2, 0, 0, 2}
*/
// Time Complexity O(N^3)
vector< vector<int> > FourSum(vector<int>& nums, int target) {
  if(nums.size() < 4) return {};
  vector< vector<int> > res;
  sort(nums.begin(), nums.end());
  for(int i = 0; i < nums.size() - 3; ++i) {
    for(int j = i + 1; j < nums.size() - 2; ++j) {
      int start = j + 1;
      int end = nums.size() - 1;
      while(start < end) {
        int sum = nums[i] + nums[j] + nums[start] + nums[end];
        if(sum == target) {
          vector<int> tmp;
          tmp.push_back(nums[i]);
          tmp.push_back(nums[j]);
          tmp.push_back(nums[start]);
          tmp.push_back(nums[end]);
          res.push_back(tmp);
          start++;
          --end;
        } else if(sum < target) start++;
        else end--;
      }
    }
  }
  sort(res.begin(), res.end());
  res.resize(unique(res.begin(), res.end()) - res.begin());
  return res;
}

int main(void) {
  vector<int> nums{1, 1, 1, 1, 1};
  vector< vector<int> > res = FourSum(nums, 4);
  for(int i = 0; i < res.size(); ++i) {
    for(int j = 0; j < res[i].size(); ++j) {
      cout << res[i][j] << " ";
    }
    cout << endl;
  }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值