首页 > 代码库 > [leetcode-18-4Sum]
[leetcode-18-4Sum]
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<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int>>result; const int size = nums.size(); if (size < 4) return result; sort(nums.begin(), nums.end()); vector<int>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; }
参考:
http://cs-cjl.com/2016/07_04_leetcode_18_4sum
[leetcode-18-4Sum]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。