class Solution
{
public:
vector<vector<int> > fourSum(vector<int> &num, int target)
{
vector<vector<int>> resultSet;
int n = num.size();
if (n < 4)
{
return resultSet;
}
sort(num.begin(), num.end());
vector<int> result(4);
for (int dIndex = n  1; dIndex >= 3; dIndex)
{
if ((dIndex < (n  1)) && (num[dIndex + 1] == num[dIndex]))
{
continue;
}
result[3] = num[dIndex];
for (int cIndex = dIndex  1; cIndex >= 2; cIndex)
{
if ((cIndex < (dIndex  1)) && (num[cIndex + 1] == num[cIndex]))
{
continue;
}
int threeSum = target  num[dIndex]  num[cIndex];
result[2] = num[cIndex];
int start = 0;
int end = cIndex  1;
while (start < end)
{
int curSum = num[start] + num[end];
if (curSum == threeSum)
{
result[0] = num[start];
result[1] = num[end];
resultSet.push_back(result);
do
{
start++;
end;
} while (start < end && num[start] == num[start  1] && num[end] == num[end + 1]);
}
else if (curSum > threeSum)
{
end;
}
else
{
start++;
}
}
}
}
return resultSet;
}
};
Looking for more efficient solution, mine is O(n^3)


Hi aqin, I was thinking dp before but then I give up. How could you define your dp array to store any possible subsum value, I mean assume target is 3, it is possible to have 2, 10 or any other value in sum of any two or three numbers. If you indeed found a dp accepted solution, could you post it for reference? Thank you in advanced!

Yes, I know the recursion but in your example, the possible value of the second index(targetvar[n]) can be any possible values since the target changes as well every time you added one number in this solution.For clarify, let me assume num=[3,1,1],target=0 then the targetvar[n] can be 03, 01,0(1),013,01+1,03+1. So for first declare the array dp, how do you know the size of second index before compute all possible subsum? Thanks for you reply!!