TA的每日心情 | 开心 昨天 06:36 |
---|
签到天数: 15 天 [LV.4]偶尔看看III
管理员
- 积分
- 1308
|
发表于 2024-3-16 18:29:17
|
显示全部楼层
- class Solution {
- public:
- vector<vector<int>> twoSum(vector<int>& nums, long target, int left){
- int right = nums.size() - 1;
- long sum2;
- vector<vector<int>> ans;
- while(left < right){
- sum2 = (long) nums[left] + nums[right];
- if(sum2 > target){
- right--;
- }else if(sum2 < target){
- left++;
- }else{
- ans.push采用back({nums[left], nums[right]});
- left++;
- right--;
- while(left < right && nums[right] == nums[right+1]){
- right--;
- }
- while(left < right && nums[left] == nums[left-1]){
- left++;
- }
- }
- }
- return ans;
- }
- vector<vector<int>> nSum(vector<int>& nums, long target, int n, int left){
- vector<vector<int>> ans;
- vector<vector<int>> ans1;
- if(n == 2){
- ans = twoSum(nums, target, left);
- }else{
- for(int i=left; i<=nums.size() - n; i++){
- if(i > left && nums[i] == nums[i-1]){
- continue;
- }
- ans1 = nSum(nums, target - nums[i], n-1, i+1);
- for(int j=0; j<ans1.size(); j++){
- ans1[j].insert(ans1[j].begin(), nums[i]);
- }
- ans.insert(ans.end(), ans1.begin(), ans1.end());
- }
- }
- return ans;
- }
- vector<vector<int>> fourSum(vector<int>& nums, int target) {
- vector<vector<int>> ans;
- sort(nums.begin(), nums.end());
- int n = nums.size();
- if(n < 4){
- return ans;
- }
- ans = nSum(nums, (long)target, 4, 0);
- return ans;
- }
- };
-
复制代码 |
|