time-complexity - 递归的时间复杂度
问题描述
下面是一个在三角形中找到最大和的算法。我想说这个算法是 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 ) ;
}
解决方案
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)
推荐阅读
- javascript - 使用外部 API 调用和 findOneAndUpdate 循环结果
- ios - 如何使用 FIrebase 将带有对象的字典附加到数组中
- python - 将烧瓶与 joblib 一起使用
- java - 调用方法
- angular - Angular 模拟多个 HTTP 调用
- javascript - 使用 group 对数组进行排序
- node.js - 如何在从调用函数返回之前等待 Node.JS 中的异步 http 请求结果?
- javascript - 安卓的 MaskedViewIOS 替代品?
- ibm-cloud - 将 IBM COS 中的 jar 添加到 WATSON 笔记本
- javascript - 从 4 级 json 对象数组中返回特定的 json 项