zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
    
     
    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    4408: [Fjoi 2016]神秘数
    UOJ #35. 后缀排序[后缀数组详细整理]
    POJ 2887 Big String
    搜索过滤grep(win下为findstr)
    解决putty自动断开的问题
    > >> 将错误输出到文件
    环境变量
    端口被占用,查看并杀死占用端口的进程
    查找文件路径find
    【vim使用】
  • 原文地址:https://www.cnblogs.com/itdef/p/14140615.html
Copyright © 2011-2022 走看看