2014.2.27 02:03
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog"
,
dict = ["cat", "cats", "and", "sand", "dog"]
.
A solution is ["cats and dog", "cat sand dog"]
.
Solution:
This problem request you to find out all breaking methods.
I tried DFS, but first I got an TLE because I looked up the segment in the dictionary in the recursive function. Later I realized it would be better to look up every segment in the dictionary and store the result in a 2d array.
After this optimization things should be good enough, but the result was still TLE.
Then I changed the direction of DFS, from right to left and got an AC at last. Don't know why, maybe the input data will tell me. Forget about it, pal.
Total time complexity is O(n!). Space complexity is O(n^2).
Accepted code:
1 // 3CE, 2TLE, 1WA, 1AC, DFS from right to left will do, while from left to right it wouldn't. 2 class Solution { 3 public: 4 vector<string> wordBreak(string s, unordered_set<string> &dict) { 5 result.clear(); 6 n = (int)s.length(); 7 if (n == 0 || dict.empty()) { 8 return result; 9 } 10 11 dp.resize(n); 12 int i, j; 13 for (i = 0; i < n; ++i) { 14 dp[i].resize(n - i); 15 } 16 17 string str; 18 for (i = 0; i < n; ++i) { 19 for (j = i; j < n; ++j) { 20 str = s.substr(i, j - i + 1); 21 if (dict.find(str) != dict.end()) { 22 dp[i][j - i] = 1; 23 } else { 24 dp[i][j - i] = 0; 25 } 26 } 27 } 28 29 words.clear(); 30 dfs(s, n - 1); 31 for (i = 0; i < n; ++i) { 32 dp[i].clear(); 33 } 34 dp.clear(); 35 36 return result; 37 } 38 private: 39 int n; 40 vector<string> result; 41 vector<string> words; 42 vector<vector<int> > dp; 43 44 void dfs(const string &s, int idx) { 45 if (idx == -1) { 46 getResultString(); 47 } else { 48 int i; 49 for (i = 0; i <= idx; ++i) { 50 if (dp[i][idx - i]) { 51 words.push_back(s.substr(i, idx - i + 1)); 52 dfs(s, i - 1); 53 words.pop_back(); 54 } 55 } 56 } 57 } 58 59 void getResultString() { 60 if (words.empty()) { 61 return; 62 } 63 string str = words[(int)words.size() - 1]; 64 int i; 65 for (i = (int)words.size() - 2; i >= 0; --i) { 66 str += (" " + words[i]); 67 } 68 result.push_back(str); 69 } 70 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)