[LeetCode]Word Break
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
思路:回溯+递归=超时
1 class Solution { 2 public: 3 bool wordBreak(string s, unordered_set<string> &dict) { 4 if(dict.find(s)!=dict.end()) return true; 5 int len=s.size(); 6 for(int i=1;i<=len;i++) 7 { 8 if(dict.find(s.substr(0,i))!=dict.end()) 9 { 10 string str=s.substr(i,len-i); 11 //return wordBreak(str,dict); 12 if(wordBreak(str,dict)) return true; 13 } 14 } 15 return false; 16 } 17 };
备忘录法,记忆化搜索。
class Solution { public: bool wordBreak(string s, unordered_set<string> &dict) { if(dict.find(s)!=dict.end()) return true; int len=s.size(); vector<bool> dp(len+1,false); dp[0]=true; for(int i=1;i<=len;i++) { for(int j=0;j<i;j++) { if(dp[i]=dp[j]&&(dict.find(s.substr(j,i-j))!=dict.end())) break; } } return dp[len]; } };