Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
題目的意思是:給出一個整型陣列,找出所有三個元素的組合,其組合之和等於0。要求在結果中不含重複組合
可以先將陣列排序,從頭依次挑選出第一個元素,在其後選兩個元素。這樣將3Sum轉換成2Sum了。
充分利用有序的屬性,使用分別在首尾的兩指標來挑選兩個元素。
注意重複組合的過濾
class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { vector<vector<int> > res; if(num.size() < 3) return res; sort(num.begin(),num.end()); for(int i = 0 ; i < num.size()-2; ++ i){ if(num[i] > 0) break; //第一個數如果大於0,則後面的數肯定大於0 if(i > 0 && num[i] == num[i-1]) continue; //去除重複的元素 int start = i+1, end = num.size()-1; while(start < end){ int sum = num[start]+num[end]+num[i]; if(sum < 0) start++; else if(sum > 0 ) end--; else { vector<int> a; a.push_back(num[i]); a.push_back(num[start]); a.push_back(num[end]); res.push_back(a); //忽略可能相同的結果 do{start++;}while(start<end && num[start] == num[start-1]); do{end--;}while(start<end && num[end] == num[end+1]); } } } return res; } };