139. Word Break

https://leetcode.com/problems/word-break/

solution

An n-character string has 2^(n–1) different segmentations (there are n–1 positions between characters, each of which can either be or not be a word boundary).

  • 动态规划

# - 完全背包: dp[i]含义: s[i-1]是否可被word切割
# - 1维dp: 容量为j的背包,所背的物品价值可以最大为dp[j]
# - 先物品还是先背包:因为不完全背包1维需要从后往前,
# - 背后从前到后还是从后到前

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        n = len(s)
        dp = [False] * (n + 1)
        dp[0] = True

        for i in range(1, n + 1):
            for j in range(i):
                # 注意是 s[j:i]
                if dp[j] and s[j:i] in wordDict:
                    dp[i] = True
        return dp[-1]

时间复杂度:O(n^2 * k) 空间复杂度:O(n)

  • dfs with memorization

时间复杂度:O() 空间复杂度:O()

follow up

140. Word Break II

  • DFS枚举每次切词的位置,使用Memorization优化(回溯+动态规划思想),每个字符串只用求一遍

时间复杂度:O() 空间复杂度:O()

  • Trie

472 Concatenated Words

word segmentation by n-gram

Last updated