foursum 问题
问题描述:
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:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- The solution set must not contain duplicate quadruplets.
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<vector<int> > fourSum(vector<int> &num, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function int i , j , m , n; set<vector<int> >revalue; vector<int> entry(4); int count=num.size(); sort(num.begin(),num.end()); for(i=0 ; i< count ; i++){ int middle=target-num[i];//num combination for(j=i+1 ; j< count ; j++){ m=j+1; n=count-1; int inner=middle-num[j]; for(;m<n;){ if(num[m]+num[n]<inner) m++; else if(num[m]+num[n]==inner){ entry[0]=num[i]; entry[1]=num[j]; entry[2]=num[m]; entry[3]=num[n]; sort(entry.begin(),entry.end()); revalue.insert(entry); m++; n--; } else n--; } } } vector<vector<int> > last(revalue.begin(),revalue.end()); return last; } };
这是leetcode里面的foursum问题,我的解法是在threesum的基础上继续加一重循环,没想到这样居然通过了……我后来查了一下看看有没有比我的o(n3)时间复杂度还好的,暂时没有看到