Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Time complexity 递归时间复杂度_Time Complexity - Fatal编程技术网

Time complexity 递归时间复杂度

Time complexity 递归时间复杂度,time-complexity,Time Complexity,下面是一个在三角形中求最大和的算法。我想说这个算法是O(N^2),因为findMax函数调用可以替换为一个嵌套的for循环,该循环遍历每个节点的每个子节点。然而,递归使我不确定。那么,如何通过递归判断代码的时间复杂度呢 int maxValue = 0; void findMax ( Node * n , int sum ) { if ( n == NULL ) { if ( maxValue < sum ) { maxValue = sum ;

下面是一个在三角形中求最大和的算法。我想说这个算法是O(N^2),因为findMax函数调用可以替换为一个嵌套的for循环,该循环遍历每个节点的每个子节点。然而,递归使我不确定。那么,如何通过递归判断代码的时间复杂度呢

int maxValue = 0;

void findMax ( Node * n , int sum ) {

if ( n == NULL ) {

    if ( maxValue < sum ) {

        maxValue = sum ;

    }

    return ;

}

findMax (n - > leftChild , sum + n - > value ) ;

findMax (n - > rightChild , sum + n - > value ) ;
}
intmaxvalue=0;
void findMax(节点*n,整数和){
如果(n==NULL){
如果(最大值<总和){
最大值=总和;
}
返回;
}
findMax(n->leftChild,sum+n->value);
findMax(n->rightChild,sum+n->value);
}
int maxValue=0;//将执行一次so(1)。
void findMax(节点*n,整数和){
if(n==NULL){//将在每次函数调用中执行,因此,如果考虑函数被调用的次数是C乘以O(C)
如果前一个if正确,那么将执行if(maxValueleftChild,sum+n->value);//访问每个节点的每个左子节点
findMax(n->rightChild,sum+n->value);//访问每个节点的每个右子节点
//因此,如果在节点之间有n个节点和m个连接(边),则我们至少访问每个节点一次:
//O(n+m+C(C'+C'+1))=O(n+m)+O(K)
int maxValue = 0; // will be executed once so O(1).

void findMax ( Node * n , int sum ) {

if ( n == NULL ) { // Will be executed in every call of function so if considering the function is called C times it is O(C)

    if ( maxValue < sum ) { // will be executed if the previous if is right so O(c')

        maxValue = sum ; // will be exceuted if the previous if is right so O(c')

    }

    return ; // will be executed once so O(1)

}

findMax (n - > leftChild , sum + n - > value ) ; // visiting every left child of each node

findMax (n - > rightChild , sum + n - > value ) ; // visiting every right child of each node 

// so we are visiting every node at least once if we have n node and m connections(edges) between nodes we have:
// O(n+m+C(c'+c'+1))=O(n+m) + O(K)