C++ | Leetcode C++题解之第140题单词拆分II

作者 : admin 本文共525个字,预计阅读时间需要2分钟 发布时间: 2024-06-10 共2人阅读

题目:

C++ | Leetcode C++题解之第140题单词拆分II插图

题解

class Solution {
private:
    unordered_map<int, vector> ans;
    unordered_set wordSet;

public:
    vector wordBreak(string s, vector& wordDict) {
        wordSet = unordered_set(wordDict.begin(), wordDict.end());
        backtrack(s, 0);
        return ans[0];
    }

    void backtrack(const string& s, int index) {
        if (!ans.count(index)) {
            if (index == s.size()) {
                ans[index] = {""};
                return;
            }
            ans[index] = {};
            for (int i = index + 1; i <= s.size(); ++i) {
                string word = s.substr(index, i - index);
                if (wordSet.count(word)) {
                    backtrack(s, i);
                    for (const string& succ: ans[i]) {
                        ans[index].push_back(succ.empty() ? word : word + " " + succ);
                    }
                }
            }
        }
    }
};
本站无任何商业行为
个人在线分享 » C++ | Leetcode C++题解之第140题单词拆分II
E-->