#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> total;
int n = nums.size();
if (n < 4)
return total;
else
{
sort(nums.begin(),nums.end());
if ((nums[0] + nums[1] + nums[2] + nums[3] > target) | (nums[n - 4] + nums[n - 3] + nums[n - 2] + nums[n - 1] < target))
return total;
else
{
int a, b, c, d;
for(a=0;a<n-3;++a)
for(b=a+1;b<n-2;++b)
for(c=b+1;c<n-1;++c)
for (d = c + 1; d < n; ++d)
{
if (nums[a] + nums[b] + nums[c] + nums[d] == target)
total.push_back(vector<int>{nums[a], nums[b], nums[c], nums[d]});
}
}
}
return total;
}
};
void main()
{
cout << "Please input target:";
int target;
cin.clear();
cin >> target;
cout << "Please input an array and use '*' to end input:";
vector<int> nums;
int ele;
while (1)
{
cin>>ele;
if (cin.fail())
break;
else {
nums.push_back(ele);
}
}
vector<vector<int>> total;
Solution S;
total = S.fourSum(nums, target);
for (int i = 0; i<total.size(); i++)
{
for (int j = 0; j<total[i].size(); j++)
cout << total[i][j] << " ";
cout << endl;
}
}
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> total;
int n = nums.size();
if (n < 4)
return total;
else
{
sort(nums.begin(),nums.end());
if ((nums[0] + nums[1] + nums[2] + nums[3] > target) | (nums[n - 4] + nums[n - 3] + nums[n - 2] + nums[n - 1] < target))
return total;
else
{
int a, b, c, d;
for(a=0;a<n-3;++a)
for(b=a+1;b<n-2;++b)
for(c=b+1;c<n-1;++c)
for (d = c + 1; d < n; ++d)
{
if (nums[a] + nums[b] + nums[c] + nums[d] == target)
total.push_back(vector<int>{nums[a], nums[b], nums[c], nums[d]});
}
}
}
return total;
}
};
void main()
{
cout << "Please input target:";
int target;
cin.clear();
cin >> target;
cout << "Please input an array and use '*' to end input:";
vector<int> nums;
int ele;
while (1)
{
cin>>ele;
if (cin.fail())
break;
else {
nums.push_back(ele);
}
}
vector<vector<int>> total;
Solution S;
total = S.fourSum(nums, target);
for (int i = 0; i<total.size(); i++)
{
for (int j = 0; j<total[i].size(); j++)
cout << total[i][j] << " ";
cout << endl;
}
}