zoukankan      html  css  js  c++  java
  • 18. 四数之和

    给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

    注意:

    答案中不可以包含重复的四元组。

    示例:

    给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。

    满足要求的四元组集合为:
    [
    [-1, 0, 0, 1],
    [-2, -1, 1, 2],
    [-2, 0, 0, 2]
    ]

    /*
    解题思路:
    解法的思路跟 3Sum 基本没啥区别,就是多加了一层 for 循环
    注意去重处理
    */
    #include<iostream>
    #include<vector>
    #include<algorithm>
    using namespace std;
    class Solution {
    public:
    	vector<int> ns;
    	vector<vector<int>> ans;
    	bool isok(vector<vector<int>> ans, int i, int j, int k)
    	{
    		for (int u = 0; u < ans.size(); u++)
    		{
    			if (i == ans[u][0] && j == ans[u][1] && k == ans[u][2])
    				return false;
    		}
    		return true;
    	}
    	vector<vector<int>> fourSum(vector<int>& nums, int target) 
    	{
    		sort(nums.begin(), nums.end());
    		int N = nums.size();
    		for (int i = 0; i < N - 3; i++)
    		for (int j = i + 1; j<N - 2; j++)
    		for (int k = j + 1; k <= N - 1; k++)
    		for (int l = k + 1; l<N; l++)
    		if (nums[i] + nums[j] + nums[k] + nums[l] == target)
    		{
    			if (isok(ans, nums[i], nums[j], nums[k]))
    			{
    				ns.push_back(nums[i]);   
    				ns.push_back(nums[j]);
    				ns.push_back(nums[k]);   
    				ns.push_back(nums[l]);
    				ans.push_back(ns);       
    				ns.clear();
    			}
    		}
    		return ans;
    	}
    };
    int main(){
    	vector<int>nums;
    	int target;
    	cin >> target;
    	int a[1000];
    	int i = 0;
    	int x;
    	while (cin >> a[i])
    	{
    		x = cin.get();
    		if (x == '
    ')
    			break;
    		nums.push_back(a[i]);
    		++i;
    	}
    	vector<vector<int>>A = Solution().fourSum(nums, target);
    	for (int i = 0; i < A.size(); i++)
    		for (int j = 0; j < A[0].size(); j++)
    			cout << A[i][j] << " ";
    		    cout << endl;
    	system("pause");
    	return 0;
    }
    

      

  • 相关阅读:
    蓝桥杯 十六进制转八进制
    蓝桥杯 字母图形
    2017.12.13T19_B2_5mianshiti
    2017.11.21T19_B2_6.2讲义
    2017.12.13T19_B2_6zuoye
    2017.12.1T19_B2_5zuoye
    2017.12.1T19_B2_4zuoye
    2017.12.1T19_B2_4——2
    2017.12.1T19_B2_4.3kehouzuoye
    2017.12.1T19_B2_4.2
  • 原文地址:https://www.cnblogs.com/277223178dudu/p/11407139.html
Copyright © 2011-2022 走看看