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. 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] ]思路:
类似3sum求和,然后在过程中及时约束,判断是否可以提前跳出循环来优化。
vector> fourSum(vector & nums, int target) { vector >result; const int size = nums.size(); if (size < 4) return result; sort(nums.begin(), nums.end()); vector temp; for (int i = 0; i < size - 3; i++) { if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) break;//及时跳出循环 if (nums[i] + nums[size - 3] + nums[size - 2] + nums[size - 1] < target)continue; for (int j = i + 1; j < size-2; j++) { if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) break;//及时跳出循环 if (nums[i] + nums[j] + nums[size - 2] + nums[size - 1] < target)continue; int left = j + 1; int right = size - 1; while (left < right) { int sum = nums[i] + nums[j] + nums[left] + nums[right]; if (sum < target)left++; else if (sum > target) right--; else { temp = {nums[i],nums[j],nums[left],nums[right]};//新学一招,类似数组赋值 result.push_back(temp); while (left < right && nums[left] == temp[2])left++; while (left < right && nums[right] == temp[3])right--; } } while (j + 1 < size && nums[j + 1] == nums[j])j++; } while (i + 1 < size && nums[i + 1] == nums[i])i++; } return result; }
参考: