DFS——单词分割,原来还是要使用cached dp才能避免不超时

582. 单词拆分II

中文
English

给一字串s和单词的字典dict,在字串中增加空格来构建一个句子,并且所有单词都来自字典。
返回所有有可能的句子。

样例

样例 1:

输入:"lintcode",["de","ding","co","code","lint"]
输出:["lint code", "lint co de"]
解释:
插入一个空格是"lint code",插入两个空格是 "lint co de"

样例 2:

输入:"a",[]
输出:[]
解释:字典为空

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution:
    """
    @param: s: A string
    @param: wordDict: A set of words.
    @return: All possible sentences.
    """
    def wordBreak(self, s, wordDict):
        # write your code here
        if not s:
            return []
             
        cache = {}
        def dfs(s):
            if not s:
                return [[]]
                 
            if s in cache:
                return cache[s]
                 
            ans = []
            for i in range(len(s)):
                word = s[0:i+1]
                if word in wordDict:
                    words = dfs(s[i+1:])
                    for p in words:
                        ans.append([word] + p)
             
            cache[s] = ans
             
            return ans
         
        ans = [" ".join(l) for l in dfs(s)]
         
        return ans

 超时的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution:
    """
    @param: s: A string
    @param: wordDict: A set of words.
    @return: All possible sentences.
    """
    def wordBreak(self, s, wordDict):
        # write your code here
        def get_words_matrix(s):
            n = len(s)
            ans = collections.defaultdict(list)
            for i in range(n):
                for j in range(i, n):
                    if s[i:j+1] in wordDict:
                        ans[i].append(j)
                         
            return ans
         
        if not s:
            return []
             
        ans = []
        dp = get_words_matrix(s)
         
        def dfs(s, start, path):
            if start == len(s):
                ans.append(" ".join(path))
                return
             
            for pos in dp[start]:
                path.append(s[start:pos+1])
                dfs(s, pos+1, path)
                path.pop()
             
         
        dfs(s, start=0, path=[])
         
        return ans

 

1
2
3
4
输入
 
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]

 



posted @   bonelee  阅读(88)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2018-01-17 DNS 隐蔽通道工具资料汇总
2017-01-17 mongodb停止遇到shutdownServer failed: unauthorized: this command must run from localhost when running db without auth解决方法
2017-01-17 mongodb集群——配置服务器放分片meta信息,说明meta里包含了哪些数据信息
点击右上角即可分享
微信分享提示