【DFS + 记忆化递归】LeetCode 140. Word Break II

本文解析了LeetCode上140题WordBreak II的两种解决方案,一种是基于DFS的方法,另一种是使用记忆化递归优化的方法,并详细介绍了第二种方案的时间复杂度和空间复杂度。

LeetCode 140. Word Break II

Solution1:我的答案
纯DFS,在第31个case时超时,还是记录一下。。

class Solution { // DFS
public:
    vector<string> wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> dict(wordDict.begin(), wordDict.end());
        vector<string> res;
        string temp = "";
        int start = 0;
        my_word(s, dict, res, temp, start);
        return res;
    }

private:
    void my_word(string& s, unordered_set<string>& dict, 
                 vector<string>& res, string& temp, int start) {
        if (start == s.size()) {
            res.push_back(temp);
            return;
        } else {
            for (int i = start; i < s.size(); i++) {
                string temp_str = s.substr(start, i - start + 1);
                if (dict.count(temp_str)) {
                    if (!temp.size())
                        temp = temp_str;
                    else
                        temp += " " + temp_str;
                    my_word(s, dict, res, temp, i + 1);
                    if (temp.find(" ") != string::npos)
                        temp = temp.substr(0, temp.size() - temp_str.size() - 1);
                    else
                        temp = "";
                }
            }
        }
        return;
    }
};

Solution2:
参考花花酱:https://zxi.mytechroad.com/blog/leetcode/leetcode-140-word-break-ii/
记忆化递归真牛逼啊!!!
Time complexity: O(2n) O ( 2 n )
Space complexity: O(2n) O ( 2 n )

// Author: Huahua
class Solution {
public:
    vector<string> wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> dict(wordDict.cbegin(), wordDict.cend());
        return wordBreak(s, dict);
    }
private:
    // >> append({"cats and", "cat sand"}, "dog");
    // {"cats and dog", "cat sand dog"}
    vector<string> append(const vector<string>& prefixes, const string& word) {
        vector<string> results;
        for(const auto& prefix : prefixes)
            results.push_back(prefix + " " + word);
        return results;
    }

    const vector<string>& wordBreak(string s, unordered_set<string>& dict) {
        // Already in memory, return directly
        if(mem_.count(s)) return mem_[s];

        // Answer for s
        vector<string> ans;

        // s in dict, add it to the answer array
        if(dict.count(s)) 
            ans.push_back(s);

        for(int j=1;j<s.length();++j) {
            // Check whether right part is a word
            const string& right = s.substr(j);
            if (!dict.count(right)) continue;

            // Get the ans for left part
            const string& left = s.substr(0, j);
            const vector<string> left_ans = 
                append(wordBreak(left, dict), right);

            // Notice, can not use mem_ here,
            // since we haven't got the ans for s yet.
            ans.insert(ans.end(), left_ans.begin(), left_ans.end());
        }

        // memorize and return
        mem_[s].swap(ans);
        return mem_[s];
    }
private:
    unordered_map<string, vector<string>> mem_;
};
提供了基于BP(Back Propagation)神经网络结合PID(比例-积分-微分)控制策略的Simulink仿真模型。该模型旨在实现对杨艺所著论文《基于S函数的BP神经网络PID控制器及Simulink仿真》中的理论进行实践验证。在Matlab 2016b环境下开发,经过测试,确保能够正常运行,适合学习和研究神经网络在控制系统中的应用。 特点 集成BP神经网络:模型中集成了BP神经网络用于提升PID控制器的性能,使之能更好地适应复杂控制环境。 PID控制优化:利用神经网络的自学习能力,对传统的PID控制算法进行了智能调整,提高控制精度和稳定性。 S函数应用:展示了如何在Simulink中通过S函数嵌入MATLAB代码,实现BP神经网络的定制化逻辑。 兼容性说明:虽然开发于Matlab 2016b,但理论上兼容后续版本,可能会需要调整少量配置以适配不同版本的Matlab。 使用指南 环境要求:确保你的电脑上安装有Matlab 2016b或更高版本。 模型加载: 下载本仓库到本地。 在Matlab中打开.slx文件。 运行仿真: 调整模型参数前,请先熟悉各模块功能和输入输出设置。 运行整个模型,观察控制效果。 参数调整: 用户可以自由调节神经网络的层数、节点数以及PID控制器的参数,探索不同的控制性能。 学习和修改: 通过阅读模型中的注释和查阅相关文献,加深对BP神经网络与PID控制结合的理解。 如需修改S函数内的MATLAB代码,建议有一定的MATLAB编程基础。
#include <iostream> #include <vector> #include <string> #include <unordered_set> #include <algorithm> #include <functional> using namespace std; class Solution { public: bool wordBreak(string s, vector<string>& wordDict) { if (wordDict.empty()) return false; // 计算字典中最长单词长度 (兼容C++17) int max_len = 0; for (const auto& word : wordDict) { max_len = max(max_len, static_cast<int>(word.length())); } // 字典存入哈希集合 unordered_set<string> words(wordDict.begin(), wordDict.end()); int n = s.length(); // 记忆化数组:-1=未计算, 0=false, 1=true vector<int> memo(n + 1, -1); // 递归lambda函数 (C++17兼容写法) function<bool(int)> dfs = [&](int i) { if (i == 0) return true; if (memo[i] != -1) return memo[i] == 1; // 从右向左检查可能的单词 for (int j = i - 1; j >= max(i - max_len, 0); --j) { string sub = s.substr(j, i - j); if (words.find(sub) != words.end() && dfs(j)) { memo[i] = 1; return true; } } memo[i] = 0; return false; }; return dfs(n); } }; int main() { Solution sol; // 测试用例1:基本功能 vector<string> dict1 = { "leet", "code" }; cout << "Test 1: " << boolalpha << sol.wordBreak("leetcode", dict1) << endl; // true // 测试用例2:重叠匹配 vector<string> dict2 = { "apple", "pen" }; cout << "Test 2: " << boolalpha << sol.wordBreak("applepenapple", dict2) << endl; // true // 测试用例3:无法匹配 vector<string> dict3 = { "cats", "dog", "sand", "and", "cat" }; cout << "Test 3: " << boolalpha << sol.wordBreak("catsandog", dict3) << endl; // false // 测试用例4:边界情况 vector<string> dict4 = { "a" }; cout << "Test 4: " << boolalpha << sol.wordBreak("a", dict4) << endl; // true // 测试用例5:长字符串性能 vector<string> dict5 = { "aa", "aaa", "aaaa", "aaaaa" }; cout << "Test 5: " << boolalpha << sol.wordBreak("aaaaaaaaaa", dict5) << endl; // true return 0; } 通俗解释
08-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值