Python code [ Time Limit Exceeded], anyone will help to improve it?


  • 0
    M
    def backtracking(self,num,candidates,target,res):
        s =sum(num)
        if s == target:
            st = sorted(num)
            if st not in res:
                res.append(st)
        else:            
            for val in candidates:
                if s + val>target:
                    break
                t = [d for d in num]
                t.append(val)                    
                self.backtracking(t,candidates,target,res)
        return res
    def combinationSum(self, candidates, target):
        candidates = sorted(candidates)
        return self.backtracking([],candidates,target,[])

  • 0
    D
    1. You can adjust target when recursively call backtracking. Thus you don't need to calculate the sum of num.

    2. Do u really need to sort num in self.backtracking()? You have sorted candidates already

    3. Use other ways than "if st not in res" to remove duplicates. Using set, though not the fastest way, should be better than this one


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.