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.
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)
Subscribe to see which companies asked this question
class Solution { public: /* * 固定两个点,然后使用two sum 求解 * 注意去掉重复的点 */ void two_sum(vector<int>& nums, vector<vector<int>>& res, int start_index, int last_index, int target) { int i = start_index + 1; int j = last_index - 1; while (i < j) { if (nums[i] + nums[j] == target) { vector<int> tmp; tmp.push_back(nums[start_index]); tmp.push_back(nums[i]); tmp.push_back(nums[j]); tmp.push_back(nums[last_index]); res.push_back(tmp); cout << nums[start_index] << nums[i] << nums[j] << nums[last_index] << endl; i++; while (nums[i] == nums[i-1]) { i++; } j--; while (nums[j] == nums[j+1]) { j--; } } else if (nums[i] + nums[j] > target) { j--; } else { i++; } } } vector<vector<int>> fourSum(vector<int>& nums, int target) { int size = nums.size(); vector<vector<int>> res; sort(nums.begin(), nums.end()); int i; int j; for (i=0; i<size-2; i++) { //过滤掉相同的左边点,防止出现重复的结果 if (i > 0 && nums[i] == nums[i-1]) { continue; } for (j=size-1; j>i+1; j--) { if (j < size-1 && nums[j] == nums[j+1]) { continue; } two_sum(nums, res, i, j, target- nums[i] - nums[j]); } } return res; } };
posted on 2016-01-06 22:24 walkwalkwalk 阅读(174) 评论(0) 编辑 收藏 举报