【发布时间】:2023-06-08 08:11:02
【问题描述】:
今天我正在解决断词问题,但我无法计算实施解决方案的时间复杂度。
这是一个问题:- https://practice.geeksforgeeks.org/problems/word-break-part-2/0/
我们必须从测试用例提供的字典中包含的单词中找到并打印由给定字符串组成的每个句子。
示例:- string = "snakesandladder", dictionary = ["snake", "snakes", "and", "sand", "ladder"]。
一个解决方案是[“蛇和梯”,“蛇沙梯”]。
我实现的功能:-
set<vector<string>> res; `//stores all the sentences`
vector<string> v; `//stores all the words in a sentence`
helper(s, st, 0); `//function call`
void helper(string& s, unordered_set<string>& st, int i){
`//string s is the string and unordered_set<string> st is the dictionary.`
if(i == s.size()){
res.insert(v);
return;
}
string temp = "";
for(int k = i ; k < s.size() ; k++){
temp += s[k];
if(st.find(temp) != st.end()){
v.push_back(temp);
helper(s, st, k+1);
v.pop_back(); `//Backtracking to find more solution`
}
}
}
我的计算表明时间复杂度应该是 O(n^n)。
【问题讨论】:
-
你为什么认为是
n^n? -
helper的复杂度是s的大小和st的大小的函数。在最坏的情况下,您会在s中找到st的所有字词。 -
@ChrisMM
for循环将运行n次(即字符串的长度)进行一次调用,每次在哈希表中成功查找后,我们将再次继续此过程对于剩余的字符串(即来自 k+1)。在最坏的情况下,我们将在字典中找到1 to n子字符串的长度。 (这是我的想法) -
@Botje 请原谅我,但我没有得到你。但我认为“在最坏的情况下,你会在
s中找到st的所有单词”这将导致O(n^n)。
标签: c++ string recursion time-complexity backtracking