Python代码的时间复杂度和空间复杂度

时间:2020-10-21 01:39:33

标签: python time-complexity big-o space-complexity code-complexity

有人可以帮助我解决此代码段的时间和空间复杂性吗?请参考leetcode问题-分词ii。给定一个非空字符串s和一个包含非空单词列表的字典wordDict,在s中添加空格以构成一个句子,其中每个单词都是一个有效的字典单词。返回所有可能的句子。

def wordBreak(self, s, wordDict):
    dp = {}
    def word_break(s):
        if s in dp:
            return dp[s]
        result = []
        for w in wordDict:
            if s[:len(w)] == w:
                if len(w) == len(s):
                    result.append(w)
                else:
                    tmp = word_break(s[len(w):])
                    for t in tmp:
                        result.append(w + " " + t)
        dp[s] = result
        return result
    
    return word_break(s)

1 个答案:

答案 0 :(得分:0)

  • 对于时间复杂度分析,几乎总是将最坏的情况考虑在内。

  • 我猜想O(N ^ 3)运行时和O(N)内存是正确的。

  • 以下是细分:

def wordBreak(self, s, wordDict):
    dp = {}
    def word_break(s):
        # This block would be O(N) 
        if s in dp: # order of N
            return dp[s]
        result = []

        # This block would be O(N ^ 2)
        for w in wordDict: # order of N
            if s[:len(w)] == w:
                if len(w) == len(s):
                    result.append(w)
                else:
                    tmp = word_break(s[len(w):])
                    for t in tmp: # order of N
                        result.append(w + " " + t)
        dp[s] = result
        return result
    
    return word_break(s) # This'd be O(N) itself
  • 因此,第二个块的O(N ^ 2)乘以调用O(N)的{​​{1}},最终将其设为word_break(s)

  • 我们可以将其简化为:

O(N ^ 3)

这将使其更易于查看:

  • class Solution: def wordBreak(self, s, words): dp = [False] * len(s) for i in range(len(s)): # order of N for word in words: # order of N k = i - len(word) if word == s[k + 1:i + 1] and (dp[k] or k == -1): # order of N dp[i] = True return dp[-1] 是N的顺序;
    • for i in range(len(s)):是N的顺序;
      • for word in words:是N的顺序;