Leetcode#15 3Sum

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.