Given array of integer numbers to find all possible returns of 4Sum Array in c++ || c ||leetcode problem.
program :
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> fourSum(vector<int> &nums, int t)
{
sort(nums.begin(), nums.end());
int n = nums.size();
set<vector<int>> st;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
for (int k = j + 1; k < n; k++)
{
int x = (long long)t - (long long)nums[i] - (long long)nums[j] - (long long)nums[k];
if (binary_search(nums.begin() + k + 1, nums.end(), x))
{
vector<int> v;
v.push_back(nums[i]);
v.push_back(nums[j]);
v.push_back(nums[k]);
v.push_back(x);
sort(v.begin(), v.end());
st.insert(v);
}
}
}
}
vector<vector<int>> ans(st.begin(), st.end());
return ans;
}
int main()
{
vector<int> arr{4, 3, 3, 4, 4, 2, 1, 2, 1, 1};
int elmt = 9;
vector<vector<int>> sum = fourSum(arr, elmt);
for (int i = 0; i < sum.size(); i++)
{
for (int j = 0; j < sum[i].size(); j++)
{
cout << sum[i][j] << " ";
}
cout << endl;
}
return 0;
}
0 Comments