139 单词的组成
1 class Solution { 2 public: 3 bool wordBreak(string s, vector<string>& wordDict) { 4 auto wordDictSet = unordered_set <string> (wordDict.begin(). wordDict.end()); 5 7 auto dp = vector <bool> (s.size() + 1); 8 dp[0] = true; 9 for (int i = 1; i <= s.size(); ++i) { 10 for (int j = 0; j < i; ++j) { 11 if (dp[j] && wordDictSet.find(s.substr(j, i - j)) != wordDictSet.end()) { 12 dp[i] = true; 13 break; 14 } 15 } 16 } 17 18 return dp[s.size()]; 19 } 20 };
个人错误思路: 递归,理论上是可行的。 不过时间复杂度太高,递归深度太深。
void checkComposeHelp(string s, vector<string> & wordDict, bool & canComposed){ if(s.length() == 0){ canComposed = true; return; } for(int i = 0; i < wordDict.size(); ++i){ int findPos = s.find(wordDict[i]); if(findPos == 0 || (findPos != string::npos && findPos + wordDict[i].length() == s.length())){ string sBak(s); sBak = sBak.erase(findPos, wordDict[i].length()); checkComposeHelp(sBak, wordDict, canComposed); 1 if (canComposed){ return; } }else{ continue; } } return; } bool wordBreak(string s, vector<string>& wordDict) { bool canComposed = false; sort(wordDict.begin(), wordDict.end(), [](string one, string another){return one.length() > another.length();}); checkComposeHelp(s,wordDict, canComposed); return canComposed; }

浙公网安备 33010602011771号