time - TimeComplexity : O(n) VS O(2^n)
问题描述
Given the following two functions, why is the time complexity of the first n while the second is 2^n?
The only difference is the +1 before the return in the second function. I don't see how that can influence the time complexity.
int f1(int n){
if (n==1)
return 1;
return f1(f1(n-1));
}
int f2(int n){
if (n==1)
return 1;
return 1+f2(f2(n-1));
}
解决方案
这里的关键见解是 f1 总是返回一个,给定任何东西,并且 f1(1) 在恒定时间内进行评估。
这些函数中的每一个都将导致两个递归调用——首先是内部递归调用,然后是外部递归调用——除非 n 为 1。在这种情况下,该函数将评估零递归调用。
但是,由于函数 f1 无论其输入如何总是返回 1,因此它进行的递归调用之一,即外部递归调用,将始终在 n 为 1 时调用。因此 f1 的时间复杂度降低到 f(n ) = f(n-1) 这是 O(n) - 因为它会进行的唯一其他调用需要 O(1) 时间。
另一方面,当计算 f2 时,内部递归调用将在 n-1 上调用,外部递归调用也将在 n-1 上调用,因为 f2(n) 产生 n。你可以通过归纳看到这一点。根据定义,f2 of 1 为 1。假设 f2(n) = n。然后根据定义 f2(n+1) 产生 1 + f2(f2(n+1-1)),根据归纳假设,它减少为 1 + (n+1-1) 或仅 n+1。
因此,每次调用 f2(n) 都会导致两次调用 f2(n-1) 的次数。这意味着 O(2^n) 时间复杂度。
推荐阅读
- javascript - 在单击下拉菜单中的链接时调用 javascript 函数时输入错误意外结束
- c# - OpenQA.Selenium.ElementNotInteractableException:无法点击元素
- node.js - 如何正确地将 http 请求包装在路由表达处理器中并推断出 HTML 中的答案?
- python - 我的程序有错误,无法找出它不起作用的原因
- laravel - php支付网关安全问题
- python-3.x - 长时间拆包时溢出 - Pytorch
- c# - 如何使用 C# 中具有标识列的 2 个查询更新 2 个 sqlserver 表?
- react-native - 在 react-360 中渲染 Three.js 场景?
- gradle - Junit Test 导入正在停止构建 gradle 项目
- c# - 使用 C# LINQ 排序