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驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    DB2 v8.2,v9.1,v9.5,v9.7下载地址及详细安装图解
    Windows Server 2008 R2遗忘管理员密码后的解决方案
    weblogic的域模式(生产模式、开发模式)
    Linux shell编程 字符串拼接
    Linux rsync命令详解
    oracle 日志组管理
    T-SQL编程规范
    数据库编程起别名的3中方式
    windows server下安装SSHD服务
    网线中的5类线、超5类线、6类线有什么区别?
  • 原文地址:https://www.cnblogs.com/itdef/p/14140615.html
Copyright © 2011-2022 走看看