下面这个是笨方法。
代码:
1 #include<iostream> 2 #include<algorithm> 3 #include<vector> 4 5 using namespace std; 6 7 vector<vector<int> > threeSum(vector<int> &num) { 8 sort(num.begin(), num.end()); 9 vector<vector<int>> result; 10 int L = num.size(); 11 for (int i = 0; i < L-2; i++) 12 { 13 if (i != 0&& num[i] == num[i - 1]) 14 { 15 continue; 16 } 17 for (int j = i+1; j < L-1; j++) 18 { 19 int OK = 0; 20 int left = j + 1; 21 int right = L - 1; 22 while (left <= right) 23 { 24 int middle = (left + right) / 2; 25 int key = 0 - num[i] - num[j]; 26 if (num[middle] == key) 27 { 28 vector<int> newV; 29 newV.push_back(num[i]); 30 newV.push_back(num[j]); 31 newV.push_back(num[middle]); 32 if (result.size() > 0) 33 { 34 if (result[result.size() - 1][0] == newV[0] && result[result.size() - 1][1] == newV[1]) 35 { 36 break; 37 } 38 } 39 result.push_back(newV); 40 OK = 1; 41 break; 42 } 43 if (OK == 1) 44 { 45 continue; 46 } 47 else 48 { 49 if (key < num[middle]) 50 { 51 right = middle-1; 52 } 53 else 54 { 55 left = middle + 1; 56 } 57 } 58 } 59 } 60 } 61 return result; 62 } 63 64 65 66 int main() 67 { 68 vector<int> S = { -1, 0, 1 ,2, -1, -4, - 1, }; 69 threeSum(S); 70 return 0; 71 }
聪明的方法: