标签:sort solution col 等于 get for tor 3sum tco
给定一个数组和一个目标数字,求数组中的4个元素之和等于目标数字,输出这4个数字所有可能的组合。
Given array nums = [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]
]
思路:
和LeetCode 15. 3Sum 很像,处理上也按 3Sum处理。在 3Sum外面再套一层循环即可。
vector<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int>> res; sort(nums.begin(), nums.end()); int n = nums.size(); for (int i = 0; i < n-3; i++) { if (i > 0 && nums[i] == nums[i - 1]) continue; for (int j = i + 1; j < n - 2; j++) { if (j > i + 1 && nums[j] == nums[j - 1]) continue; int l = j + 1, r = n - 1, remain = target - nums[i] - nums[j]; while (l < r) { if (l > j+1 && nums[l] == nums[l - 1]) { l++; continue; } if (nums[l] + nums[r] > remain) r--; else if (nums[l] + nums[r] < remain) l++; else res.push_back({ nums[i],nums[j],nums[l++],nums[r--] }); } } } return res; }
标签:sort solution col 等于 get for tor 3sum tco
原文地址:https://www.cnblogs.com/luo-c/p/12912664.html