c++ - 函数的时间复杂度是多少?
问题描述
今天我正在解决断词问题,但我无法计算实施解决方案的时间复杂度。
这是问题:- 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)。
解决方案
查看算法,最坏的情况类似于 IIII 试图在数组中找到组合:{I, I , I, I} 这意味着您从 I 开始,然后您需要检查三个 I,因此您需要第一个为 7,第二个为 7,所有这些为 7,所以想想你的问题,在最坏的情况下是 (2n-1)*n,所以在这种情况下,n 是 4,如果我们得到 28如果你想要大的 O 表示法需要计算,你会去 O(n^2) 不知道你是怎么得到 N^N 的......这是一个真正巨大的数字,只是说这令人惊讶......
推荐阅读
- python - 如何为 WxPython STC 创建自定义 Lexer
- java - 如何在其他活动中使用最终变量?
- angular - 角度绑定无法正常工作
- python - 在 Windows 10 上的 python 进程中导入 tensorflow 需要 1.5GB 的 RAM
- android - 如何将领域对象从后台线程传递给 UiThread?
- java - spring boot thymeleaf 多选数据绑定 mongodb
- react-native - react-native expo 问题:`SceneView` 的检查方法
- regex - 使用 sed 在特定文本之后删除文件名中的空格
- python - 单应性透视投影不起作用
- java - 如何将一个rdd拆分成多个rdd(横向),GC开销异常