LeetCode 140. 单词拆分 II dfs 哈希

地址  https://leetcode-cn.com/problems/word-break-ii/

复制代码
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。

说明:

分隔时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:

输入:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
输出:
[
  "cats and dog",
  "cat sand dog"
]
示例 2:

输入:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
输出:
[
  "pine apple pen apple",
  "pineapple pen apple",
  "pine applepen apple"
]
解释: 注意你可以重复使用字典中的单词。
示例 3:

输入:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
输出:
[]

 
复制代码

算法1
上来就是一阵操作 暴力DFS
果然就是TLE了。还是非常严重的TLE那种
后面利用哈希记录对应的字符串拆解成功的方案 才能AC

C++ 代码

复制代码
class Solution {
public:
    unordered_map<string, vector<string>> mm;

    vector<string> dfs(string s, const vector<string>& wordDict){
        if (mm.count(s) != 0) return mm[s];
        if (s.empty()) return {""};
        vector<string> ret;
        for (auto& e : wordDict) {
            if (e[0] == s[0] && s.substr(0, e.size()) == e)
            {
                vector<string> last;
                last = dfs(s.substr(e.size()), wordDict);
                for (auto& ee : last)
                    ret.push_back(e + (ee.empty() ? "" : " ") + ee);
            }
        }

        mm[s] = ret;
        return ret;
    }

    vector<string> wordBreak(string s, vector<string>& wordDict) {
        dfs(s, wordDict);
        vector<string> ans =  mm[s];
        return ans;
    }
};


 
复制代码

 

posted on   itdef  阅读(127)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
历史上的今天:
2019-12-15 LeetCode 1289 下降路径最小和 II Minimum Falling Path Sum II
2019-12-15 LeetCode 1288. 删除被覆盖区间 Remove Covered Intervals
2019-12-15 LeetCode 1287. 有序数组中出现次数超过25%的元素 Element Appearing More Than 25% In Sorted Array
2019-12-15 LeetCode 1286. 字母组合迭代器 Iterator for Combination

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示