1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89

#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;
}
View Program Text


Test Status