class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        int len = nums.size();
        sort(nums.begin(),nums.end());
       
        vector<vector<int>> ans ;
       
       
        for(int i = 0 ; i < len - 3 ; i ++)
        {
            if(nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target)break;
            if(nums[i] + nums[len - 1] + nums[len - 2] + nums[len - 3] < target)continue;
           
            for(int j = i + 1 ; j < len - 2; j ++)
            {
                if(nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target)break;
                if(nums[i] + nums[j] + nums[len - 1] + nums[len - 2] < target)continue;
               
                int key = target - (nums[i] + nums[j]);
                int left = j + 1;
                int right = len - 1;
                while(left < right)
                {
                    int k = nums[left] + nums[right];
                    if(k < key){
                        left ++;
                    }else if( k > key){
                        right --;
                    }else{
                        vector<int> sol ;
                        sol.push_back(nums[i]);
                        sol.push_back(nums[j]);
                        sol.push_back(nums[left]);
                        sol.push_back(nums[right]);
                        ans.push_back(sol);
                        while(nums[left] == nums[left + 1])left ++;
                        left ++;
                    }
                }
                while(nums[j] == nums[j+1])j++;
            }
            while(nums[i] == nums[i+1])i++;
        }
        return ans;
    }
};

posted on 2018-01-21 14:33  朽木の半夏  阅读(117)  评论(0编辑  收藏  举报