LeetCode_3 sum

Given an array S of n integers, are there elements a, b, c 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)

双指针的思想。使用DFS球排列组合时去重复的思想去重复

class Solution {

public:

    vector<vector<int> > threeSum(vector<int> &num) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        vector<vector<int>> res;

        sort(num.begin(), num.end());

        int len = num.size();

        if(len < 3) return res;

        

        for(int i = 0; i <= len -3 ; ++i)

        {

            while(i> 0 && i <= len -3 && num[i] == num[i-1]) ++i;

            if(i > len -3) break;

            int low = i + 1;

            int high = len -1;

            while(low < high){

            

                int sum = num[i] + num[low] + num[high];

                if(sum == 0){

                    vector<int> tp;

                    tp.push_back(num[i]);

                    tp.push_back(num[low]);

                    tp.push_back(num[high]);

                    res.push_back(tp);

                    ++low;

                    while(low < high && num[low] == num[low-1])++low;

                    --high;

                    while(low <high && num[high] == num[high+1]) --high;

                }else if(sum < 0){

                    ++low;

                    while(low < high && num[low] == num[low-1])++low;

                }else{

                    --high;

                    while(low < high && num[high] == num[high+1]) --high;

                }

            }

        }

        

        return res;

    }

};

 

你可能感兴趣的:(LeetCode)