Original title Address
With 2sum, 3sum, 4sum, 3sum closest series, see this article
Sort +dfs+ Pruning + two-point search
What if the last element does not have a binary lookup time out??
Code:
1vector<vector<int> >Res;2 3 voidDFS (vector<int> &num, vector<int> ans,intPosintLeftintsum) {4 if(left = =0) {5 if(Sum = =0)6 res.push_back (ans);7 return;8 }9 Ten if(left = =1) { One intL =Pos; A intR = num.size ()-1; - while(L <=r) { - intm = (L + r)/2; the if(Num[m] + sum = =0) { - Ans.push_back (num[m]); - res.push_back (ans); - Ans.pop_back (); + return; - } + Else if(Num[m] + sum <0) AL = m +1; at Else -r = M-1; - } - return; - } - inunordered_set<int>Old ; - for(inti = pos; I < num.size (); i++) { to if(Old.find (num[i])! =old.end ()) + Continue; - if(Sum + Left * Num[i] >0) the Break; * if(sum + num[i] + (left-1) * Num[num.size ()-1] <0) $ Continue;Panax Notoginseng Old.insert (Num[i]); - Ans.push_back (Num[i]); theDFS (num, ans, i +1, left-1, Sum +num[i]); + Ans.pop_back (); A } the } + -vector<vector<int> > Threesum (vector<int> &num) { $ sort (Num.begin (), Num.end ()); $DFS (NUM, vector<int> (),0,3,0); - returnRes; -}
Leetcode#15 3Sum