First, the topic
Given an array S of n integers, is 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 is 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)
Second, the idea
My thinking has been very simple, at the time of 2Sum, is to add the problem into a search problem, set a number a, to find target-a in the remaining number. 3Sum did the same, but it was much less efficient. And it gives the output all possible combinations of answers that involve repetitive problems.
Practice or in accordance with the change of the sum for the query, set a A, B, find target-(a+b), the only optimization is to use a hash table to save the existing (a, b), so as not to do a duplicate search. But this is not the way after all, do 4sum will be 4 layer cycle, not a thing. Look at other people's answers, from both sides toward the middle, this is very good. Prepare to try this method in 3Sum closet.
Third, the Code
1 classSolution:2 #@param {integer[]} nums3 #@return {integer[][]}4 defthreesum (Self, nums):5 Nums.sort ()6Passed_list = []7result = []8Record = {}9Result_dict = {}Ten ifLen (Nums) < 3: One return [] A Else: - forIinchRange (len (nums)): - forJinchRange (i + 1, Len (nums)): theA =Nums[i] -b =Nums[j] - if(A, B)inchRecord: - Pass + Else: -Record[(A, b)] =0 +target = 0-a-b A ifTargetinchNums[j + 1:]: at Passed_list.append (a) - Passed_list.append (b) - passed_list.append (target) - ifSTR (passed_list)inchresult_dict: -Passed_list = [] - Pass in Else: - result.append (passed_list) toResult_dict[str (passed_list)] =0 +Passed_list = [] - returnResult
Iv. Summary
Prepare to finish all the n-sum problems, and then summarize the rules of this type of problem.
[Leetcode] #13 3sum