3sum leetcode (15)

来源:互联网 发布:网易是什么软件 编辑:程序博客网 时间:2024/06/05 13:31

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.

    For example, given array S = {-1 0 1 2 -1 -4},    A solution set is:    (-1, 0, 1)    (-1, -1, 2)

这个问题主要递归调用 2sum 题目中给了两个条件,
1是必须顺序输出,那么首先进行排序,
另外一个不能输出重复的,所以我们就要剪枝,遇到重复的值就跳过。

<span style="font-size:24px;">#include <iostream>#include <vector>#include <algorithm>using namespace std;class Solution{public:    vector<vector<int>> threeSum(vector<int>& nums)    {        vector<vector<int>>  vs;        int n = nums.size();        if(n<3)        {            return vs;        }        sort(nums.begin(),nums.end());        for(int i=0;i<n-2;)        {            int value = -nums[i];            int temp = nums[i];            vector<int> v = twoSUm(nums,value,i+1,n-1);            int vsize = v.size();            for(int j=0;j<vsize;)            {                vector<int> v2;                v2.push_back(nums[i]);                v2.push_back(v[j++]);                v2.push_back(v[j++]);                vs.push_back(v2);            }            while(i<n-2&&nums[i+1]==temp)            {                i++;            }
<span style="white-space:pre"></span>i++;        }    }    vector<int> twoSUm(vector<int>& nums,int value,int startindex,int endindex)    {        vector<int> v;        while(startindex<endindex)        {            if(nums[startindex] + nums[endindex] == value)            {                v.push_back(nums[startindex]);                v.push_back(nums[endindex]);                while(startindex<endindex && nums[startindex] == nums[startindex+1])                {                    startindex++;                }                startindex++;                 while(startindex<endindex && nums[endindex] == nums[endindex-1])                {                    endindex--;                }            }            else if(nums[startindex] + nums[endindex]<value)            {                startindex++;            }            else            {                endindex--;            }        }        return v;    }};int main(){    vector<int> v  =  {14,-11,-2,-3,4,-3,-3,-8,-15,11,11,-6,-14,-13,5,-10,-13,0,-12,-8,14,-12,-10,2,-4,9,13,10,2,7,-2,-7,4,11,5,-7,-15,10,-7,-14,6,11,-5,7,6,8,5,8,-7,8,-15,14,11,13,1,-15,7,0,10,-14,14,-15,-14,3,4,6,4,4,-7,12,5,14,0,8,7,13,1,-11,-2,9,12,-1,8,0,-11,-5,0,11,2,-13,4,1,-12,5,-10,-1,-12,9,-12,-11,-2,9,-12,5,-6,2,4,10,6,-13,4,3,-7,-11,11,-3,-9,-4,-15,8,-9,-4,-13,-14,8,14};       Solution s;    s.threeSum(v);    return 0;}</span>


0 0
原创粉丝点击