1. 程式人生 > >leetcode140 Word Break II

leetcode140 Word Break II

思路:

直接爆搜會超時,需要使用記憶化搜尋。使用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 };