../ Competitive Programming
-rw-r--r--aguang1.1 KiB1 min read

Leet Code Daily 2024-05-25 - Word Break II

Solution

DFS

Code

c++
class Solution {
public:
    unordered_set<string> wordSet;
    vector<string> wordNow;
    vector<string> ans;

    void dfs(string& s, int i) {
        if (i == s.size()) {
            string sentence;
            for (const auto& w : wordNow) {
                if (sentence.size() > 0) {
                    sentence += " ";
                }
                sentence += w;
            }
            ans.push_back(sentence);
            return;
        }
        for (int j = i + 1; j <= s.size(); j++) {
            string new_word = s.substr(i, j - i);
            if (wordSet.contains(new_word)) {
                wordNow.push_back(new_word);
                dfs(s, j);
                wordNow.pop_back();
            }
        }
    }

    vector<string> wordBreak(string s, vector<string>& wordDict) {
        wordSet = unordered_set<string>(wordDict.begin(), wordDict.end());
        dfs(s, 0);
        return ans;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window