leetcode -- 4sum

class Solution {
public:
    vector<vector<int> > ret;
    vector<int> subret;
public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
     sort(num.begin(),num.end());
     int upperbase = 0, base = 1,left = 2,right = num.size() - 1;
     for(upperbase = 0;upperbase< num.size();upperbase++)
     {
         if(upperbase != 0 && num[upperbase] == num[upperbase -1]) continue;
         for(base = upperbase + 1;base < num.size();base++)
         {
             if(base != upperbase + 1 && num[base] == num[base - 1]) continue;

             int left = base + 1,right = num.size() - 1;
             while(left < right)
             {
                if(left != base + 1 && num[left] == num[left - 1]) 
                 {
                        left++;continue; 
                 }
                if(right != num.size() - 1 && num[right] == num[right + 1])
                    {
                        right--;
                        continue;
                    }
                int sum = num[upperbase] + num[base] + num[left] + num[right];
                if(sum > target)
                    right--;
                else if(sum < target)
                    left++;
                else{
                subret.clear();
                subret.push_back(num[upperbase]);subret.push_back(num[base]);
                subret.push_back(num[left]);subret.push_back(num[right]);
                ret.push_back(subret);
                right--;left++;
                }
             }
         }
     }
        return ret;
    }
};

 

posted on 2014-05-28 11:12  berkeleysong  阅读(135)  评论(0编辑  收藏  举报

导航