【LeetCode】 4Sum 【Python C++】

Leetcode 494. Target Sum (python+cpp) Leetcode 494. Target Sum题目解析:解法1:recursion + memorization解法2:动态规划 题目 解析: 这个题目本质上也是个背包问题。一般来说背包问题用动态规划来解比较常见,但是这道题比较特殊,我比较推荐用recursion的方法来解。虽然从本质上来讲,recursion + memorization和动态规划是一样的,但是对于这道题木还是recursion更容易理解一些 解法1:recursion + memorization 假设在位置I,和为sum的解为F( 阅读详情

题目:

从给定的一堆数字中找出 所有 4个数之和=taget的组合。组合与组合之间不得重复

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [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]
]

解答:

#C++版本(观摩了 leetcode讨论区的大佬)
class K_Sum{
public:
    vector<vector<int>> k_Sum(vector<int>& nums,int target,int k){
        if(nums.size()<k){
            return {};
        }
        sort(nums.begin(),nums.end());
        return k_sum_helper(nums,target,k,0);
    
}
private:
    vector<vector<int>> k_sum_helper(vector<int>& nums,int target,int k,int begin_index){
        if(begin_index == nums.size() || k*nums[begin_index] > target || k*nums[nums.size()-1] <target){
            return {};
        }
        vector<vector<int>> result;
        if (k == 2) {
            for (int left = begin_index, right = nums.size() - 1; left < right;
                    ++left) {
                while (left < right && nums[left] + nums[right] > target) {
                    --right;
                }
                if (left == right) return result;
                if (nums[left] + nums[right] == target) {
                    result.push_back({nums[left], nums[right]});
                }
                else if (right != nums.size() - 1) ++right;
                while (left < right && nums[left + 1] == nums[left]) ++left;
            }
            return result;
        }
        for(int i=begin_index;i+k<=nums.size();i++){
            auto temp_result=k_sum_helper(nums,target-nums[i],k-1,i+1);
            for(auto & v :temp_result){
                v.push_back(nums[i]);
                result.emplace_back(std::move(v));
            }
            while(i+k<nums.size() && nums[i]==nums[i+1]) i++;
        }
        return result;
        
    }
};


class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        return K_Sum().k_Sum(nums, target, 4);
    }
};

#Python 版本
class Solution:
    def fourSum(self, nums, target):
        ans=[]
        nums.sort()
        for i in range(0,len(nums)):
            for j in range(i+1,len(nums)):
                k,z=j+1,len(nums)-1
                while k<z:
                    sum_=nums[i]+nums[j]+nums[k]+nums[z]
                    if sum_==target:
                        ans_1=[nums[i],nums[j],nums[k],nums[z]]
                        if ans_1 not in ans:
                            ans.append(ans_1)
                            k+=1
                            z-=1
                            continue
                        else:
                            k+=1
                            z-+1
                    else:
                        if sum_>target:
                            z-=1
                        else:
                            k+=1
    
                
        return ans

 

从理论到实践:使用Sigrity SystemSI完成DDR4信号完整性仿真全流程解析 本文详细解析了使用Sigrity SystemSI完成DDR4信号完整性仿真的全流程,从核心挑战到实战操作。文章深入探讨了DDR4信号完整性问题,介绍了SystemSI工具链的演进与分工,并提供了从前期准备到高级技巧的详细指南,帮助工程师有效解决DDR4设计中的信号完整性问题。 阅读详情

相关推荐

使用pytorch构建LSTM_AE模型的两种方式

2.基本LSTM_Unit计算——基本LSTM_AE结构 3.自定义LSTM_Unit计算——自定义LSTM_AE结构 1.LSTM-Encoder-Decoder模型结构及简要解析 图基本lstm计算单元

qq_37840762的博客 7273

【leetcode】(python) 18. 4Sum详解

目录DescriptionExample题目大意解题思路code Description 4Sum Medium Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all ...

。 389

INS/伪距组合导航(2)

伪距惯导组合导航

u014430081的博客 827

Leetcode 18.四数之和 4Sum - Python 双指针法

class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: result = [] nums.sort() length = len(nums) for i in range(length-3): if i == 0 or nums[i] != nums[i-1]: #当nums[i]与nums[.

rendalian的博客 413

保姆级图解:FD-SOI工艺流程中的关键三步(外延生长、应变硅、HKMG)

本文详细解析了FD-SOI工艺流程中的三大关键技术:外延生长、应变硅工程和HKMG集成。通过选择性外延生长技术优化接触电阻,利用应变硅提升载流子迁移率,并结合先栅高k金属栅工艺实现精准栅极控制,FD-SOI技术在智能手机处理器和自动驾驶芯片制造中展现出卓越的低功耗与高性能平衡。

weixin_29267307的博客 490

【BigWorld 游戏服务器引擎】Cell 架构设计介绍,及Java实现方案的探索

横向扩展(Scalability):通过动态增减CellApp和BaseApp的数量,可以轻松应对玩家人数的变化。世界可以做得非常大,只需增加更多的 Cell。负载分离(Load Separation):将不同性质的负载分离,避免了单一进程瓶颈。CPU 密集型的实时计算(CellApp)和 I/O 密集型的数据操作(BaseApp)互不影响。高效的视野管理(AOI):每个 Cell 只关心自己区域内和边界上的实体,大大降低了计算复杂度。容错性:某个CellApp。

代码时光 1203

18. 4Sum Leetcode Python

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in

hyperbolechi的专栏 1902

GEE必须会教程——一文教会你研究区域分块计算与合并

一整块算不是挺好的吗?emmmm,用过的人都知道,GEE好比幼年期的“紫妍”,要用“丹药”来养的,除非你是萧炎小友,到哪都有人给爆金币。我们今天想做的是计算2020年夏季西藏自治区的植被覆盖度(FVC),FVC的估算需要使用归一化植被指数(NDVI数据),这里我们用到的产品是MODIS的相关数据产品,该产品的分辨率是25 0m。下载好的结果毕竟是一块一块的,怎么对下载好的结果进行拼接,变成一张大图呢,别急,接下来,我们上科研小霸王——R语言。此处,我们通过省份数据,按照属性筛选,得到西藏自治区的行政边界。

Promising_GEO的博客 2510

LeetCode--4Sum II(4个数的和)Python

题目: 给定四个长度为N的数组:A、B、C、D,找到A[i]+B[j]+C[k]+D[l]=0的tuple个数。 解题思路: 直接对四个数组进行遍历,时间复杂度为N的4次方,超时。之后想到将哈希应用到计算过程中。先将其中两个数组的和存储到字典中,再计算另外两个数组的和的相反数有没有在之前的字典中出现,出现则将最终的count数加上其出现的次数。时间复杂度为n的2次方。 代码(Python)

诚实的小小乐 1080

Unitree G1仿人机器人协同搬箱:从仿真搭建到多机协同部署完整指南

Unitree G1仿人机器人协同搬箱技术方案摘要 本文提供了一套完整的Unitree G1人形机器人协同搬箱解决方案,涵盖从仿真环境搭建到多机协同部署的全流程。核心内容包括: 双仿真环境配置:同时搭建Gazebo+ROS Noetic基础仿真环境与Isaac Gym+Mujoco高性能RL训练环境,支持Sim2Sim迁移验证 训练框架搭建:详细配置unitree_rl_gym框架,提供PPO算法定制化训练流程和参数优化方案 数据集应用:整合宇树开源真机数据集(UnifoLM-WBT-Dataset)~~~

huanghm88的专栏 471

基于YOLOv8的MVTec AD缺陷检测系统设计与实现

速度快,精度高;支持 anchor-free 架构;支持实例分割和图像分类;模块化代码,易于部署与改进;完美兼容 ONNX、TensorRT 等推理框架;官方支持多平台训练和推理(CPU/GPU)。YOLOv8 是工业视觉检测落地非常理想的选择。MVTec AD(Anomaly Detection)数据集包括15类工业对象,每个对象包括多个子类缺陷(例如 “scratch”, “crack”, “hole”)及正常图像。类别缺陷子类bottlecablecapsule。

YOLO 931

【LeetCode】18. 4Sum 四数之和

作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录题目描述题目大意解题方法遍历相似题目参考资料日期 题目地址:https://leetcode.com/problems/4sum/description/ 题目描述 Given an array nums of n integers and an integer target, a...

负雪明烛 3584

ZYNQ BRAM实现PS与PL数据交互

有时CPU需要与PL进行小批量的数据交换,可以通过BRAM模块,也就是Block RAM实现此要求。本章通过Zynq的GP Master接口读写PL端的BRAM,实现与PL的交互。在本实验中加入了自定义的FPGA程序,并利用AXI4总线进行配置,通知其何时读写BRAM。以下为本实验原理图,CPU通过AXI BRAM Controller读取BRAM数据,CPU仅配置自定义的PL BRAM Controller 的寄存器,不通过它读写数据。

baidu_34971492的博客 2271

[leetcode]4Sum

题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note:

175

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

(每日一练C++)18. 四数之和

给你一个由 n 个整数组成的数组nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组[nums[a], nums[b], nums[c], nums[d]](若两个四元组元素一一对应,则认为两个四元组重复): 0 <= a, b, c, d< n a、b、c 和 d 互不相同 nums[a] + nums[b] + nums[c] + nums[d] == target 你可以按 任意顺序 返回答案 。 示例 1: 输入:nums = [1,....

weixin_39827856的博客 270

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

4Sum

Date:   Oct 30, 2017 Problem:   https://leetcode.com/problems/4sum/description/ Description:   Given an arraySofnintegers, are there elementsa,b,c, anddinSsuch thata+b+c+d...

diaoyaozheng2830的博客 85

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

[LeetCode] 018. 4Sum (Medium) (C++/Java/Python)

[LeetCode] 018. 4Sum (Medium) (C++/Java/Python)

水果君の日常 3513

4sum问题用python_[leetcode]4Sum @ Python

原题地址:http://oj.leetcode.com/problems/4sum/题意:从数组中找到4个数,使它们的和为target。要求去重,可能有多组解,需要都找出来。解题思路:一开始想要像3Sum那样去解题,时间复杂度为O(N^3),可无论怎么写都是Time Limited Exceeded。而同样的算法使用C++是可以通过的。说明Python的执行速度比C++慢很多。还说明了一点,大概出...

weixin_39622747的博客 100

数据结构与算法及leetcode上有关数组题目的整理003

今天总结了一下leetcode上数组的题,leetcode上数组的题实在是太多了,这里只对前150题进行了归纳,选择一些比较经典的题总结; leetcode1:Two sum 计算两个数的和等于一个目标结果,传统暴力算法:遍历两次,计算出相应的和,然后用一个vector来保存数据然后返回,时间复杂度为O(n^2); 算法改进:首先将数组进行排序,然后采用两个指针,一个指针指向数组起始的

hufanglei007的博客 360

第八章-高频考点相向双指针变形题

Two Sum 的变形Two Sum 的变形Two Sum - Data Structure DesignTwo - Unique Pairs3 SumTriangle CountTwo Sum - Closest to Target3 Sum Closest (similar to 2 sum closest)4 Sum4 Sum IIPartition ArrayInterleaving positive and negative numbersSort ColorsSort Colors IIMove

weixin_41909012的博客 279

【LeetCode】939. Minimum Area Rectangle 解题报告(Python & C++)

作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录题目描述题目大意解题方法确定对角线,找另外两点(4sum)字典保存出现的x值,y值的点日期 题目地址:https://leetcode.com/problems/minimum-area-rectangle/description/ 题目描述 Given a set of poin...

负雪明烛 2866

【LeetCode.18】4Sum (C++、Python3)

问题描述 Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum ...

anlian523的博客 454

LeetCode 15 — 3Sum(C++ Java Python)

题目:http://oj.leetcode.com/problems/3sum/ Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of ze

龙之梦 5204

4sum问题用python_[LeetCode] 018. 4Sum (Medium) (C++/Java/Python)

[LeetCode] 018. 4Sum (Medium) (C++/Java/Python)索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)Github:https://github.com/illuz/leetcode018.4Sum (Medium)链接:题目:https://oj.leetcode.com/problems/4sum/代码(...

weixin_30697511的博客 126

454. 4Sum II**

454. 4Sum II** https://leetcode.com/problems/4sum-ii/description/ 题目描述 Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l]...

珍妮的选择的博客 267

Leetcode 18. 4Sum

题目描述:找出数组中任意4个数和为target的组合,不得重复。 题目链接:Leetcode 18. 4Sum 思路:基于3Sum做待定,相当又套了一层循环。 当然,也可以暴力列举 3 3 个的情况来达到目的。 代码如下 // Author: Huahua class Solution { public: vector&lt;vector&lt;int&gt;&gt; fourSum(...

Za七杂⑧ 155
上一篇: 【LeetCode】3Sum Closest 【python c++】
下一篇: 【LeetCode】 Remove Nth Node From End of List 【python C++】做法详解
Jie Ou
博客等级 码龄10年 176粉丝 111原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值