四数之和
class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int>> result; sort(nums.begin(), nums.end()); for(int k = 0; k < nums.size(); k++){ //第一层剪枝 if(nums[k] > target && nums[k] >= 0){ break; } //对k去重 if(k > 0 && nums[k] == nums[k - 1]){ continue; } for(int i = k + 1; i < nums.size(); i++){ //剪枝 if (nums[k] + nums[i] > target && nums[k] + nums[i] >= 0) { break; } if(i > k+1 && nums[i] == nums[i - 1]){ continue; } int left = i + 1; int right = nums.size() - 1; while(right > left){ // nums[k] + nums[i] + nums[left] + nums[right] > target 会溢出 if((long)nums[k] + nums[i] + nums[left] + nums[right] > target) right--; else if((long)nums[k] + nums[i] + nums[left] + nums[right] < target) left++; else{ result.push_back(vector<int>{nums[k], nums[i], nums[left], nums[right]}); while(right > left && nums[right] == nums[right - 1]) right--; while(right > left && nums[left] == nums[left + 1]) left++; right--; left++; } } } } return result; } };
四数之和和三数之和相类似,不过外层剪枝操作更复杂,目前还不太明白,明天起来再过一遍理解理解。
标签:right,target,nums,int,&&,Day13,刷题,LeetCode,left From: https://www.cnblogs.com/tianmaster/p/16885143.html