At first glance, we will immediately think of recursion, but the cost of direct recursion is too high. When the word length in the dictionary is very small and the word length is very long, it will definitely time out. Let's take a closer look. Is it necessary to perform recursive verification every time? If it is not verified from position I, other recursive branches do not need to go when they reach this position, because it must be a dead end. When I think of creating a table, I can record the locations that cannot be used, which significantly improves the speed.
The following is a bit of implementation. It is impossible to record a location. map is the simplest and most direct, and the search speed is fast. Each time you select the step size, you do not need to go from 0 to length. My approach is to first count the longest and smallest word lengths, and each time you verify this length, you can.
The code is very simple and generally does not cause errors:
int mmin = 0x7fffffff, mmax = 0;map<int, bool> visited;bool pwordBreak(string &s, int start, unordered_set<string> &dict){ if(start >= s.length()) return true; if(visited.find(start) != visited.end()) return visited[start]; for(int i=mmin;i<=mmax&&start+i<=s.length();i++){ string sb = s.substr(start, i); if(dict.find(sb) != dict.end()){ if(pwordBreak(s, start+i, dict)){ visited[start+i] = true; return true; }else{ visited[start+i] = false; } } } return false;}class Solution {public: bool wordBreak(string s, unordered_set<string> &dict) { unordered_set<string>::const_iterator it = dict.begin(); while(it != dict.end()){ mmin = min(mmin, (int)(*it).length()); mmax = max(mmax, (int)(*it).length()); it++; } visited.clear(); return pwordBreak(s, 0, dict); }};