设为首页 加入收藏

TOP

Leetcode[18]-4Sum
2015-11-21 00:59:42 来源: 作者: 【 】 浏览:2
Tags:Leetcode -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.


分析:和上道题有点类似,多了一层循环,注意该循环的条件就行.

class Solution {
public:
    vector
   
     > fourSum(vector
    
     & nums, int target) { vector
     
       > result; int n = nums.size(); if(n < 4) return result; sort(nums.begin(),nums.end()); for(int i = 0; i < n; i++) { if(i>0 && nums[i] == nums[i-1]) continue; for(int j = i+1; j < n; j++){ if(j > i+1 && nums[j]== nums[j-1]) continue; fourNumber(nums,result,i,j,target); } } return result; } void fourNumber(vector
      
        & nums,vector
       
         > &results, int curIndex1,int curIndex2,int target){ int i = curIndex2 + 1; int j = nums.size()-1; while(i
        
          target ) j--; else { vector
         
           vec; vec.push_back(nums[curIndex1]); vec.push_back(nums[curIndex2]); vec.push_back(nums[i]); vec.push_back(nums[j]); results.push_back(vec); i++,j--; while(i < j && nums[i] == nums[i-1])i++; while(j > i && nums[j] == nums[j+1])j--; } } } };
         
        
       
      
     
    
   
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++归并算法 下一篇HDU 1532Drainage Ditches(最大流..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: