Leetcode-140. Word Break II 单词拆分 II (DP)

题目

给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。
链接:https://leetcode.com/problems/word-break-ii/

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.

Note:

  • The same word in the dictionary may be reused multiple times in the segmentation.
  • You may assume the dictionary does not contain duplicate words.

Example:

Input:
s = “catsanddog”
wordDict = [“cat”, “cats”, “and”, “sand”, “dog”]
Output:
[
“cats and dog”,
“cat sand dog”
]

思路及代码

DP
  • 递归逆序查找
  • 思路借鉴于https://zxi.mytechroad.com/blog/leetcode/leetcode-140-word-break-ii/
  • set的查询效率大大高于list:set > dict >> list
  • 从leetcode评论区看到特殊的test case会导致超时:
    • “aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa”
      [“a”,“aa”,“aaa”,“aaaa”,“aaaaa”,“aaaaaa”,“aaaaaaa”,“aaaaaaaa”,“aaaaaaaaa”,“aaaaaaaaaa”, “b”]
class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
        memo = {}
        words = set(wordDict)
        
        def wb(s):
            if s in memo:
                return memo[s]
            ans = []
            if s in words: 
                ans.append(s)
            for i in range(1, len(s)):
                right = s[i:]
                if right not in words: 
                    continue
                for w in wb(s[0:i]):
                    ans += [w + " " + right]
            memo[s] = ans.copy()
            return memo[s]
        
        return wb(s)

复杂度

T = O ( 2 n ) O(2^n) O(2n)
S = O ( 2 n ) O(2^n) O(2n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值