// C++ implementation to find valid word
// break using Recursion
#include <bits/stdc++.h>
using namespace std;
// Helper function to perform backtracking
void wordBreakHelper(string& s, unordered_set<string>& dictSet,
string& curr, vector<string>& res,
int start) {
// If start reaches the end of the string,
// save the result
if (start == s.length()) {
res.push_back(curr);
return;
}
// Try every possible substring from the current index
for (int end = start + 1; end <= s.length(); ++end) {
string word = s.substr(start, end - start);
// Check if the word exists in the dictionary
if (dictSet.count(word)) {
string prev = curr;
// Append the word to the current sentence
if (!curr.empty()) {
curr += " ";
}
curr += word;
// Recurse for the remaining string
wordBreakHelper(s, dictSet, curr, res, end);
// Backtrack to restore the current sentence
curr = prev;
}
}
}
// Main function to generate all possible sentence breaks
vector<string> wordBreak(string s, vector<string>& dict) {
// Convert dictionary vector
// to an unordered set
unordered_set<string>
dictSet(dict.begin(), dict.end());
vector<string> res;
string curr;
wordBreakHelper(s, dictSet, curr, res, 0);
return res;
}
int main() {
string s = "ilikesamsungmobile";
vector<string> dict = {"i", "like", "sam", "sung",
"samsung", "mobile", "ice",
"and", "cream", "icecream",
"man", "go", "mango"};
vector<string> result = wordBreak(s, dict);
for (string sentence : result) {
cout << sentence << endl;
}
return 0;
}