Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Execute Python-3 Online

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)

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.