Sum (leetcode 2Sum, 3Sum, 4Sum, K Sum)

Source: Internet
Author: User

Sum (leetcode 2Sum, 3Sum, 4Sum, K Sum)

(1) Preface

People who have done leetcode know that there are problems such as 2sum, 3sum (closest), and 4sum. These are also classic questions in the interview. They can check whether the sorting property can be used properly, get efficient algorithms step by step. after summing up, I think all these problems can be summarized and digested using a general K sum Sum problem. Here we will directly describe the problem of K sum and the algorithm (recursive solution ), then apply this general method to the specific K, such as the 2Sum, 3Sum, and 4Sum problems in leetcode.

There is also the number of 2, 3, and 4 closest to the target, which is the deformation of the above problem, and the idea does not change much.

(2) leetcode summation problem description (K sum problem ):

The sum of K sum is generally described as follows: give you a group of N numbers (such as vector Num), and then give you a constant (such as int target). Our goal is to find K numbers in this heap, so that the sum of these K numbers is equal to the target.

(3) Considerations

 

Note that this group of numbers may have repeated items: for example, 1 1 2 3, evaluate 3sum, and then target = 6. When you search, you may get two groups, 1 2 3, 1 2, 3, 1 comes from the first 1 or the second 1, but there is only one group of results, so the final result should be duplicated.

There are two methods for removing duplicates:

(1) mobile detection before and after, and repeated numbers are found

 

// Search for the other two possible numbers, and remove the duplicates while (++ p <q & num [P-1] = num [p]) {// do nothing} while (-- q> p & num [q + 1] = num [q]) {// do noghing}

(2) Use the STL Container set: set >

 

Set does not allow repeated values.

(4) K Sum solution, applicable to leetcode 2Sum, 3Sum, 4Sum

Method 1: brute force is to enumerate all K-subsets. The complexity is to select K from N, and the complexity is O (N ^ K)


Method 2: Sorting + greedy

This method applies to 2sum, 3sum, 3sum cloest (finding 3 numbers and closest to target), 4sum, 4sum cloest (4 numbers and closest to target ).

Overall Thinking:

2sum, on the contrary, it is easy to prove that the first pointer is shifted right until sum = target is found.

Similar to binary search, time complexity O (N)

3 sum: first sort, set the number of 1 (the outer one for loop traversal), then use the first and last double pointers to select two numbers, and still use the greedy policy to move the pointer to get 3sum = target

Time complexity O (N * N)

3 sum cloest)

4 sum: Because the greedy policy only applies to dual pointers, we need to fix 2 numbers here. How can we fix it? Double-Layer for loop traversal !!! Then we introduce the head and tail dual pointers, time complexity O (N * N)

4sum cloest: Same as above, time complexity O (N * N)

 

// 2 sumint I = starting; // header pointer int j = num. size ()-1; // tail pointer while (I <j) {int sum = num [I] + num [j]; if (sum = target) {store num [I] and num [j] somewhere; if (we need only one such pair of numbers) break; otherwise do ++ I, -- j ;} else if (sum <target) ++ I; else -- j ;}

// 3 sum // sorts the original array in non-descending (ascending) Order InsertSort (num, num. size (); for (int I = 0; I <num. size (); ++ I) {// deduplicated if (I! = 0 & num [I] = num [I-1]) continue; int p = I + 1, q = num. size ()-1; int sum = 0; // The contraction method is used to search for 2nd, 3rd while (p <q) {sum = num [I] + num [p] + num [q]; if (sum = 0) {vector
  
   
NewRes; newRes. push_back (num [I]); newRes. push_back (num [p]); newRes. push_back (num [q]); InsertSort (newRes, newRes. size (); res. push_back (newRes); // search for the other two possible numbers. Remove the while (++ p <q & num [P-1] = num [p]) {// do nothing} while (-- q> p & num [q + 1] = num [q]) {// do noghing} else if (sum <0) // and too small, p moves backward {+ + p;} else // and too large, q move forward {-- q ;}}}
  

// 3 sum cloestclass Solution {
Public: int threeSumClosest (vector
  
   
& Num, int target) {int index; bool flag = true; sort (num. begin (), num. end (); if (num. at (0) + num. at (1) + num. at (2)> target) index = num. at (0) + num. at (1) + num. at (2)-target; else {index = target-(num. at (0) + num. at (1) + num. at (2); flag = false;} for (int I = 0; I <num. size (); ++ I) {int p = I + 1, q = num. size ()-1; int sum = 0; while (p <q) {sum = num [I] + num [p] + num [q]; if (sum = target) {return sum;} // if else if (sum <target) // and too small, p moves backward {++ p; if (target-sum
   
    
//4 sumclass Solution{public:    vector
     
       > fourSum(vector
      
        &num, int target) {        // Note: The Solution object is instantiated only once.        vector
       
        > res;    int numlen = num.size();if(num.size()<4)return res;sort(num.begin(),num.end());set
        
         > tmpres;for(int i = 0; i < numlen; i++){for(int j = i+1; j < numlen; j++){int begin = j+1;int end = numlen-1;while(begin < end){int sum = num[i]+ num[j] + num[begin] + num[end];if(sum == target){vector
         
           tmp;tmp.push_back(num[i]);tmp.push_back(num[j]);tmp.push_back(num[begin]);tmp.push_back(num[end]);tmpres.insert(tmp);begin++;end--;}else if(sum
          
           >::iterator it = tmpres.begin();for(; it != tmpres.end(); it++)res.push_back(*it);return res; }};
          
         
        
       
      
     


 

 

 

 

 

 

 

 

 

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.