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

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        vector<vector<int>> ans;
        int l,r,n;
        for(int k=0;k<nums.size()-3;k++){
            l=k+1;
            r=nums.size()-1;
            while(r<l){
                n=nums[k]+nums[l]+nums[r];
                if(n==0){
                    vector<int> temp;
                    temp.push_back(nums[k]);
                    temp.push_back(nums[l]);
                    temp.push_back(nums[r]);
                    ans.push_back(temp);
                    l++;
                    r--;
                }else if(n<0){
                    l++;
                }else if(n>0){
                    r--;
                }
            }
        }
        return ans;
    }
};