Skip to content

Commit

Permalink
impl word break II
Browse files Browse the repository at this point in the history
  • Loading branch information
SKTT1Ryze committed Mar 4, 2024
1 parent fc10b3e commit 2d2b23f
Showing 1 changed file with 46 additions and 5 deletions.
51 changes: 46 additions & 5 deletions leetcode-cc/WordBreakII.hpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#include <numeric>
#include <unordered_set>
#include <utility>

#include "TestHelper.h"
Expand All @@ -11,11 +13,11 @@ IMPLEMENT_PROBLEM_CLASS(
"Given a string s and a dictionary of strings wordDict, add spaces in s to "
"construct a sentence where each word is a valid dictionary word. Return "
"all such possible sentences in any order.",
{""});
{"Backtracking"});

class SWordBreakII : public ISolution {
public:
size_t problemId() const override { return 149; }
size_t problemId() const override { return 140; }
string name() const override {
return ("Solution for " + string("Word Break II"));
}
Expand All @@ -29,14 +31,53 @@ class SWordBreakII : public ISolution {

},
{{"cats and dog", "cat sand dog"},
{"pine apple pen apple", "pineapple pen apple",
"pine applepen apple"}},
{"pineapple pen apple", "pine applepen apple",
"pine apple pen apple"}},
[this](auto input) {
return this->wordBreak(get<0>(input), get<1>(input));
});
};
int benchmark() const override { return 0; }

private:
vector<string> wordBreak(string s, vector<string>& wordDict) const {}
vector<string> wordBreak(string s, vector<string>& wordDict) const {
unordered_set<string> dict(wordDict.begin(), wordDict.end());
vector<string> current = {};
vector<string> paths = {};

this->backtracking(s, 0, 1, dict, current, paths);

return paths;
}

void backtracking(string s, int start, int end, unordered_set<string>& dict,
vector<string> current, vector<string>& paths) const {
int n = s.length();
if (start < n && end < n) {
string subs = s.substr(start, end - start);
if (dict.contains(subs)) {
this->backtracking(s, start, end + 1, dict, current, paths);
current.push_back(subs);
this->backtracking(s, end, end + 1, dict, current, paths);
} else {
this->backtracking(s, start, end + 1, dict, current, paths);
}
} else {
if (start < n) {
if (dict.contains(s.substr(start, n - start))) {
current.push_back(s.substr(start, n - start));
} else {
return;
}
}

if (!current.empty()) {
string path = accumulate(
std::next(std::begin(current)), std::end(current), current[0],
[](string ss, string s) { return ss + " " + s; });

paths.push_back(path);
}
}
}
};

0 comments on commit 2d2b23f

Please sign in to comment.