2.1.8 —线性表—3Sum

描述
Given an array S of n integers, are there elementsa, b, c inS such thata+b+c = 0? Find all uniquetriplets in the array which gives the sum of zero.
Note:
• Elements in a triplet (a, b, c)must be in non-descending order. (ie,a b c)
• The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}.
A solution set is:
(-1, 0, 1)

(-1, -1, 2)

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class ThreeSum
{
private:
	void Sort(int a[], int n);
	vector<pair<int, int>> TwoSumIsValue(int a[], int begin, int end, int value);
public:
	vector<vector<int>> ThreeSumIsValue(int a[], int n, int value);
};
void ThreeSum::Sort(int a[], int n)
{
	for (int i = 0; i < n-1; i++)
	{
		int min =i;
		for (int j=i; j < n; j++)
		{
			if (a[j] < a[min])
				min = j;
		}
		if (min != i)
		{
			int temp = a[i];
			a[i] = a[min];
			a[min] = temp;
		}
	}
}
vector<pair<int, int>> ThreeSum::TwoSumIsValue(int a[], int begin, int end, int value)
{
	vector<pair<int, int>> res;
	res.clear();
	if (begin >= end)
		return res;
	//
	while (begin < end)
	{
		if (a[begin] + a[end] == value)
		{
			res.push_back(make_pair(begin, end));
			begin++;
			end--;
		}
		else if (a[begin] + a[end]<value)
		{
			begin++;
		}
		else
		{
			end--;
		}
	}
	return res;
}
vector<vector<int>> ThreeSum::ThreeSumIsValue(int a[], int n, int value)
{
	vector<vector<int>> res;
	res.clear();
	if (n <= 2)
		return res;
	//
	Sort(a, n);
	for (int i = 0; i < n - 2; i++)
	{
		int temp = value - a[i];
		vector<pair<int, int>> res2 = TwoSumIsValue(a, i + 1, n-1, temp);
		if (res2.size()>0)
		{
			for (int j = 0; j < res2.size(); j++)
			{
				vector<int> temp_res;
				temp_res.push_back(a[i]);
				temp_res.push_back(a[res2[j].first]);
				temp_res.push_back(a[res2[j].second]);
				res.push_back(temp_res);
			}
		}
	}
	sort(res.begin(), res.end());
	res.erase(unique(res.begin(), res.end()), res.end());
	return res;
}


int main()
{
	const int n = 10;
	int a[n] = { 3, 8, -14, -14, 4, 6, 1, 9, 5, 7 };
	ThreeSum threesum;
	int value = 0;
	vector<vector<int>> res = threesum.ThreeSumIsValue(a, n, value);
	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、付费专栏及课程。

余额充值