Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
For example, given array S = {1 0 -1 0 -2 2}, and target = 0. A solution set is: (-1, 0, 0, 1) (-2, -1, 1, 2) (-2, 0, 0, 2)直接上代碼:
最主要的還是進行去重。
class Solution { public: vector> fourSum(vector &num, int target) { vector > ret; if(num.size()==0) return ret; sort(num.begin(),num.end()); for(int i = 0;i 0&&num[i] == num[i-1]) continue; for(int j = i+1;j i+1&&num[j] == num[j-1]) continue; int k = j+1,t = num.size()-1; while(k j+1&&num[k] == num[k-1])//這裡是if,而不是while.如果是while可能會越界,在每一次 {k++;continue;} //指針變化之後都要進行判斷。避免越界的發生。 //這裡是contimue,而不是break.如果是while,也不能是break,因為可能導致t指針的重復。if(ttarget) t--; else { vector v; v.push_back(num[i]); v.push_back(num[j]); v.push_back(num[k]); v.push_back(num[t]); ret.push_back(v); k++;//哪一個變化都可以 } } } } return ret; }};