Why the program would time out, I run it on my local machine it is much faster than others that can be accepted


  • 0
    G

    can anyone help me why the program also meet time limited issue when submit

    class Solution(object):
        fResult = []
        def saveResult(self,rlist,candidates):
            tmp = []
            for i in (xrange(len(rlist))):
                for j in xrange(rlist[i]):
                    tmp.append(candidates[i])
            tmp.sort()
            self.fResult.append(tmp)
    
        def myhelper(self, left, idxArray, candidates, rList):
            if (idxArray == len(candidates)):
                return
            cnt = left / candidates[idxArray]
            if cnt == 0:
                return
            for i in reversed((xrange(cnt + 1))):
                subleft = left - i * candidates[idxArray]
    
                rList.append(i)
                if (subleft) :
                    self.myhelper(subleft, idxArray + 1, candidates, rList)
                else :
                    self.saveResult(rList, candidates)
                rList.pop()
    
        def combinationSum(self, candidates, target):
            """
            :type candidates: List[int]
            :type target: int
            :rtype: List[List[int]]
            """
            left = target 
            rList = []
            candidates.sort()
            self.myhelper(left, 0, candidates, rList)
            self.fResult.sort()
            return self.fResult

  • 0

    You need to reset fResult between the test cases, something like this:

    def combinationSum(self, candidates, target):
        self.fResult = []
        ...
    

  • 0
    G

    thansk very much, after I add your answer, it works.


Log in to reply
 

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