|
发表于 2024-3-16 19:01:17
|
显示全部楼层
- class Solution {
- public:
- vector<vector<int>> result;
- vector<vector<int>> fourSum(vector<int>& nums, int target) {
- sort(nums.begin(),nums.end());
- vector<int> leaf;
- int n = 4;
- if(nums.size()==n){//剪枝
- long long temp=0;
- for(int i=0;i<n;i++){
- temp+=nums[i];
- }
- if(temp==target)
- result.push采用back(nums);
- return result;
- }
-
- nSum(nums,0,target,n,leaf);
- return result;
- }
- void nSum(const vector<int>& nums,int index,long long target,int n,vector<int>& leaf){
- if(n==2){
- int left=index,right=nums.size()-1;
- while(left<right){
- if(nums[left]+nums[right]<target){
- left++;
- while(left<right&&nums[left-1]==nums[left])//去重
- left++;
- }
- else if(nums[left]+nums[right]>target){
- right--;
- while(left<right&&nums[right+1]==nums[right])
- right--;
- }
- else{
- leaf.push采用back(nums[left]);
- leaf.push采用back(nums[right]);
- result.push采用back(leaf);
- leaf.pop采用back();
- leaf.pop采用back();
- //继续寻找
- left++;
- while(left<right&&nums[left-1]==nums[left])
- left++;
- }
- }
- return;
- }
- if(n>2&&nums.size()-index>=n) {
- for(int i=index;i<nums.size()-n+1;i++){
- //去重
- if(i>index&&nums[i]==nums[i-1])
- continue;
- //-----超限剪枝
- long long temp = nums[i],temp2=nums[i];
- for(int j=1;j<n;j++){
- temp+=nums[i+j];
- temp2+=nums[nums.size()-j];
- }
- if(temp>target||temp2<target)
- continue;
- //----------
- leaf.push采用back(nums[i]);
- nSum(nums, i+1, target-nums[i],n-1, leaf);
- leaf.pop采用back();
- }
- }
- }
- };
-
复制代码 |
|