【发布时间】:2020-09-10 05:45:07
【问题描述】:
问题陈述: 给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在 s 中添加空格以构造一个句子,其中每个单词都是一个有效的字典单词。返回所有可能的句子。
注意:
字典中的同一个词可能会在分词中重复使用多次。 您可以假设字典不包含重复的单词。
示例测试用例:
Input:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output:
[
"cats and dog",
"cat sand dog"
]
我的解决方案:
class Solution {
unordered_set<string> words;
unordered_map<string, vector<string> > memo;
public:
vector<string> getAllSentences(string s) {
if(s.size()==0){
return {""};
}
if(memo.count(s)) {
return memo[s];
}
string curWord = ""; vector<string> result;
for(int i = 0; i < s.size(); i++ ) {
curWord+=s[i];
if(words.count(curWord)) {
auto sentences = getAllSentences(s.substr(i+1));
for(string s : sentences) {
string sentence = curWord + ((int)s.size()>0? ((" ") + s) : "");
result.push_back(sentence);
}
}
}
return memo[s] = result;
}
vector<string> wordBreak(string s, vector<string>& wordDict) {
for(auto word : wordDict) {
words.insert(word);
}
return getAllSentences(s);
}
};
我不确定时间和空间的复杂性。我认为它应该是 2^n ,其中 n 是给定字符串 s 的长度。谁能帮我证明时间和空间的复杂性?
我还有以下几个问题:
- 如果我不在 getAllSentences 函数中使用备忘录,那将是什么 这种情况下的时间复杂度?
- 还有比这更好的解决方案吗?
【问题讨论】:
标签: algorithm time-complexity dynamic-programming space-complexity