• [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:

    • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, abcd)
    • 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)
    

    思考:在3Sum的基础上,再加一个循环。

    class Solution {
    public:
        vector<vector<int> > fourSum(vector<int> &num, int target) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
    		sort(num.begin(),num.end());
    		int i,j,k,m,sum;
    		vector<vector<int> > ret;
    		for(i=0;i!=num.size();i++)
    		{
    			if(i&&num[i]==num[i-1]) continue;
    			for(j=i+1;j!=num.size();j++)
    			{
    				if(j>i+1&&num[j]==num[j-1]) continue; 
    				k=j+1;
    				m=num.size()-1;
    				while(k<m)
    				{
    					if(k>j+1&&num[k]==num[k-1])
    					{
    						k++;
    						continue;
    					}
    					if(m<num.size()-1&&num[m]==num[m+1])
    					{
    						m--;
    						continue;
    					}
    					sum=num[i]+num[j]+num[k]+num[m];
    					if(sum==target)
    					{
    						vector<int> ans;
    						ans.push_back(num[i]);
    						ans.push_back(num[j]);
    						ans.push_back(num[k]);
    						ans.push_back(num[m]);
    						ret.push_back(ans);
    						k++;
    						m--;
    					}
    					else if(sum<target) k++;
    					else m--;				
    				}
    			}
    		}
    		return ret;
        }
    };
    

      

  • 相关阅读:
    finereport 文档
    FineRport 工作用
    SQL 排序
    fineReport
    python | Mysql 索引优化分析
    python | 缓存穿透、缓存雪崩和缓存击穿面试题
    python | Jenkins构建Spring Boot 详细步骤
    python | MySQL全面查询的正则匹配
    python | TCP 三次握手和四次挥手图解(有限状态机)
    python | 3款工具实现快速K8S开发
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3416073.html
Copyright © 2020-2023  润新知