#15. 3Sum

来源:互联网 发布:python 依赖注入 编辑:程序博客网 时间:2024/06/10 05:16

题目描述:

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: 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]
]

这个直观的想肯定是暴力搜索三重循环,就算用三重循环还要解决重复元素的问题,虽然重复元素可以用但是解答方案是不能重复的,这就牵扯到一些细节,参考了别人的解答过程。

class Solution {public:    //该算法还是三重搜索 利用逻辑优化了中间一部分 去除了重复部分     vector<vector<int> > threeSum(vector<int>& nums) {        vector<vector<int> > result;        vector<int> temp;        sort(nums.begin(),nums.end());        for(int i =0;i<nums.size();i++){            //开始必须是负数 否则不可能构成0             if(nums[i]>0)                break;            //求得的最终结果中没有重复的 在这里消除重复项             if(i>0 && nums[i] == nums[i-1])                continue;            int target = 0 - nums[i];            int start = i+1,end = nums.size()-1;            //两头凑 加快进程            while(start<end){                if(nums[start]+nums[end]==target){                    temp.clear();                    temp.push_back(nums[i]);                    temp.push_back(nums[start]);                    temp.push_back(nums[end]);                    result.push_back(temp);                    //消除重复步骤                    while(start<end&&nums[start]==nums[start+1])                        start++;                    while(start<end&&nums[end]==nums[end-1])                        end--;                     start++;                    end--;                }else if(nums[start]+nums[end]<target){                    start++;                }else{                    end--;                }            }         }        return result;    }};

三个数的和本身想的是两个数的和先建一张表,和一张map,然后遍历表在map中查找键值,这样复杂度大概可以到O(n^2),但是这样就不好处理中间的重复值了,有推荐说用set可以直接避免重复的值。
直觉上这道题是不是貌似得用动态规划?