思路:
直接爆搜会超时,需要使用记忆化搜索。使用map把已经计算过的情况记录下来,避免重复计算。
实现:
1 class Solution 2 { 3 public: 4 vector<string> wordBreak(string s, vector<string>& wordDict) 5 { 6 unordered_map<int, vector<string>> dp; 7 return dfs(s, 0, wordDict, dp); 8 } 9 vector<string> dfs(string s, int cur, vector<string>& wordDict, unordered_map<int, vector<string>>& dp) 10 { 11 if (cur >= s.length()) 12 { 13 vector<string> v; 14 v.push_back(""); 15 return v; 16 } 17 if (dp.count(cur)) return dp[cur]; 18 vector<string> ans; 19 for (auto it: wordDict) 20 { 21 int l = it.length(); 22 if (cur + l <= s.length() && s.substr(cur, l) == it) 23 { 24 if (cur + l == s.length()) 25 ans.push_back(it); 26 else 27 { 28 vector<string> tmp = dfs(s, cur + l, wordDict, dp); 29 for (auto it1: tmp) 30 { 31 ans.push_back(it + " " + it1); 32 } 33 } 34 } 35 } 36 return dp[cur] = ans; 37 } 38 };