(-1, -1, 2)
第一种做法是DFS 其解是NP hard是通解所有sub array的问题,所以过不了test但是自己机子是可以跑的。先贴在这里,
class Solution: # @return a list of lists of length 3, [[val1,val2,val3]] def dfs(self,num,valuelist,start,solution): if len(valuelist)==3 and valuelist not in solution: solution.append(valuelist) for index in range(start,len(num)): valuelist=valuelist+[num[index]] self.dfs(num,valuelist,index+1,solution) valuelist=valuelist[:len(valuelist)-1] def threeSum(self, num): solution=[] num.sort() self.dfs(num,[],0,solution) return solution
当num[i]+num[left]+num[right]==0时候就得到想要的解。否则当和小于0时left=left+1 和大于0则right=right-1
This method‘s time complexity is O(n^2), we need to sort the array first, then we use three pointers, the first pointer is the index from 0 to len(num-1)
the second pointer is left=i+1 the third pointer is right=len(num)-1, while left<right we check the num[i]+num[left]+num[right] if the value is 0 we add it to the solution.
if sum is less than 0 we increase left otherwise decrease right.
class Solution: # @return a list of lists of length 3, [[val1,val2,val3]] def threeSum(self, num): solution=[] num.sort() for i in range(len(num)-1): if i>0 and num[i]==num[i-1]: continue left=i+1 right=len(num)-1 while left<right: val=num[i]+num[left]+num[right] if val==0 and [num[i],num[left],num[right]] not in solution: solution.append([num[i],num[left],num[right]]) left=left+1 right=right-1 elif val<0: left=left+1 else: right=right-1 return solution
原文地址:http://blog.csdn.net/hyperbolechi/article/details/42803209