从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)。非常感谢任何帮助!