1. Pure Recursive Backtracking without Cache
Intuition
Maintain current path of chosen words. If start == s.length, join path with spaces and add to results. For end from start + 1 to s.length: if s[start...end-1] in dictionary, push word to path, recurse on end, and pop word upon backtracking.
When to apply: Basic baseline comparison.
Algorithm
- Initialize
res = []andpath = []. - Helper
backtrack(start): - If
start == s.length:res.push(path.join(' ')); return. - For
endfromstart + 1tos.length: -
w = s.substr(start, end - start). - If
dict.contains(w): -
path.push(w). -
backtrack(end). -
path.pop(). - Return
res.
#include <iostream>#include <string>#include <vector>#include <unordered_set> class Solution { void backtrack(int start, const std::string& s, const std::unordered_set<std::string>& dict, std::vector<std::string>& current, std::vector<std::string>& res) { if (start == (int)s.size()) { std::string sentence = ""; for (int i = 0; i < (int)current.size(); ++i) { if (i > 0) sentence += " "; sentence += current[i]; } res.push_back(sentence); return; } for (int end = start + 1; end <= (int)s.size(); ++end) { std::string word = s.substr(start, end - start); if (dict.count(word)) { current.push_back(word); backtrack(end, s, dict, current, res); current.pop_back(); } } }public: std::vector<std::string> wordBreak(std::string s, std::vector<std::string>& wordDict) { std::unordered_set<std::string> dict(wordDict.begin(), wordDict.end()); std::vector<std::string> res, current; backtrack(0, s, dict, current, res); return res; }}; int main() { Solution sol; std::vector<std::string> dict = {"cat","cats","and","sand","dog"}; auto ans = sol.wordBreak("catsanddog", dict); for (const auto& sent : ans) std::cout << sent << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^N * N)— In the worst case where all prefixes are valid, generates 2N paths of length N. - Space complexity:
O(N) call stack
Why Brute Force Doesn't Scale:
Memoizing suffix sentences guarantees each suffix is parsed at most once.
Only stores reachable, successful sub-sentence lists.