4
什么是取自代码递归地解决了这个时间复杂度:http://www.geeksforgeeks.org/dynamic-programming-set-32-word-break-problem/:分词的递归解决方案的时间复杂度?
// returns true if string can be segmented into space separated
// words, otherwise returns false
bool wordBreak(string str)
{
int size = str.size();
// Base case
if (size == 0) return true;
// Try all prefixes of lengths from 1 to size
for (int i=1; i<=size; i++)
{
// The parameter for dictionaryContains is str.substr(0, i)
// str.substr(0, i) which is prefix (of input string) of
// length 'i'. We first check whether current prefix is in
// dictionary. Then we recursively check for remaining string
// str.substr(i, size-i) which is suffix of length size-i
if (dictionaryContains(str.substr(0, i)) &&
wordBreak(str.substr(i, size-i)))
return true;
}
// If we have tried all prefixes and none of them worked
return false;
}
我想其n^2,因为对于n调用的方法,最坏的情况做(N -1)工作(递归地遍历剩余的字符串?)。或者它是指数/ n!?
我很难搞清楚这些递归函数的Big(O)。任何帮助深表感谢!