Time Limitted Error in Python Code


  • 0
    D

    Hi, I have implemented my algorithm in python, however it has the time limitted error. I think I am using DP to solve the problem but why does this error come out?

    class Solution:
    def wordBreak(self, s, dict):
        length=len(s)+1
        res=[]
        result=[]
        for i in range(length):
            res.append(False)
            result.append([])
        res[0]=True
        for i in range(length-1):
            if s[0:i] in dict:
                result[i].append(s[0:i])
        for i in range(length-1):
            for j in range(i+1):
                if res[j]==True and s[j:(i+1)] in dict:
                    res[i+1]=True
                    for it in result[j]:
                        result[i+1].append(it+" "+s[j:(i+1)])
        if res[length-1]:
            return  result[-1]
        else:
            return []

Log in to reply
 

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