原题
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, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.
- 1
- 2
- 3
- 4
- 5
- 6
题目大意
给定一个整数数组,找出a + b + c + d = target的唯一解。
解题思路
先确定a和d的两个数,对于a和d两个数,不能同时重复使用。然后再确定b和c,同样这两个数也不能同时重复使用。找出所有满足条件的解,同时可以保证解不重复。
#include <stdio.h>
#include <vector>
int Partition(int *v, const int low, const int high)
{
if (v == NULL || low > high) {
return -1;
}
int i = low;
int j = high;
int pivot = v[i];
while (i < j) {
while (i < j && pivot < v[j]) {
--j;
}
if (i < j) {
v[i++] = v[j];
}
while (i < j && pivot > v[i]) {
++i;
}
if (i < j) {
v[j--] = v[i];
}
}
v[i] = pivot;
return i;
}
void QuickSort(int *v, const int low, const int high)
{
if (v == NULL || low > high) {
return ;
}
if (low < high) {
int pivot = Partition(v, low, high);
QuickSort(v, low, pivot - 1);
QuickSort(v, pivot + 1, high);
}
}
bool Func(int *v, const int len, const int sum, std::vector<std::vector<int> > &vec)
{
bool ret = false;
if (v == NULL || len < 4) {
return ret;
}
QuickSort(v, 0, len - 1);
// 第一个加数
for (int i = 0; i < len - 3; ++i) {
// 第一个加数使用不能重复
if (i > 0 && v[i] == v[i - 1]) {
continue;
}
// 第二个加数
for (int j = len - 1; j > i + 2; --j) {
// 第二个加数使用不能重复
if (j < len - 1 && v[j] == v[j + 1]) {
continue;
}
// 第三个加数
int start = i + 1;
// 第四个加数
int end = j - 1;
int n = sum - v[i] - v[j];
while (start < end) {
if (v[start] + v[end] == n) {
std::vector<int> vecs;
vecs.push_back(v[i]);
vecs.push_back(v[start]);
vecs.push_back(v[end]);
vecs.push_back(v[j]);
vec.push_back(vecs);
// 保证再次使用第二个数不重复
do {
++start;
} while (start < end && v[start] == v[start - 1]);
// 保证再次使用第三个数不重复
do {
--end;
} while (start < end && v[end] == v[end + 1]);
} else if (v[start] + v[end] < n) {
// 保证再次使用第二个数不重复
do {
++start;
} while (start < end && v[start] == v[start - 1]);
} else {
// 保证再次使用第三个数不重复
do {
--end;
} while (start < end && v[end] == v[end + 1]);
}
} // end while
} // end j
} // end i
return ret;
}
int main()
{
int v[] = {1,3,5,7,9,0,8,6,4,2};
const int len = sizeof(v) / sizeof(v[0]);
int sum = 10;
std::vector<std::vector<int> > vec;
Func(v, len, sum, vec);
QuickSort(v, 0, len - 1);
for (int i = 0; i < vec.size(); ++i) {
std::vector<int> vecs = vec[i];
for (int j = 0; j < vecs.size(); ++j) {
printf("%d ", vecs.at(j));
}
printf("\n");
}
return 0;
}
[root@agan tmall]# g++ -o sum sum.cc
[root@agan tmall]# ./sum
0 1 2 7
0 1 3 6
0 1 4 5
0 2 3 5
1 2 3 4