#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

void twoSum(vector<int> &num, size_t choosenIndex, vector<vector<int> > &results) 
{
    size_t low = choosenIndex+1;
    size_t high = num.size()-1;
    int target = -num[choosenIndex];
    while (low < high) 
    {
        int sum = num[low] + num[high];
        if (target < sum)
        {
            --high;
        }
        else if (sum < target)
        {
            ++low;
        }
        else 
        {
            results.push_back(vector<int>());
            results.back().push_back(num[choosenIndex]);
            results.back().push_back(num[low]);
            results.back().push_back(num[high]);

            do
            {
                ++low;
            } while (low < high && num[low-1] == num[low]);
            
            do
            {
                --high;
            } while (low < high && num[high] == num[high+1]);
        }
    }
}

vector<vector<int> > threeSum(vector<int> &num) 
{
    vector<vector<int> > results;
    size_t size = num.size();

    if (size < 3) return results;
    
    sort(num.begin(), num.end());

    int val = num[0]-1; // simply make val different with first number
    for (int i = 0; i < size; ++i)
    {
        if (val == num[0]) continue;

        val = num[i];
        twoSum(num, i, results);
    }

    return results;
}

ostream & operator <<(ostream & out, vector<vector<int> > &vv)
{
    for (size_t i = 0; i < vv.size(); ++i)
    {
        vector<int> &v = vv[i];
        for (size_t j = 0; j < v.size(); ++j)
        {
            out << v[j] << ", ";
        }
        out << endl;
    }
    
    return out;
}

int main(int argc, char const *argv[])
{
    int a[] = {-1,0,1,2,-1,-4};
    int sa = sizeof(a)/sizeof(int);
    vector<int> va(a, a+sa);

    vector<vector<int> > result = threeSum(va);
    cout << result;

    return 0;
}