class FourSum: def __init__(self,inp,target): self.inp = inp self.inp.sort() self.target = target self.tmp_solutions = set([]) def recurse(self,tmp_sol,candidates): if len(tmp_sol)==4 and sum(tmp_sol)==self.target: tmp_sol.sort() self.solutions.add(tuple(tmp_sol)) elif len(tmp_sol)>4: return None else: for i,num in enumerate(self.inp): j = i while self.inp[j]==self.inp[i]: j+=1 if j>=len(self.inp): break self.recurse(tmp_sol+[num],candidates[j:]) inp = [1, 0, -1, 0, -2, 2] target = 0 s = FourSum(inp,target) s.recurse([],s.inp)
We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy. Accept Learn more