查看: 1141| 回复: 2
跳转到指定楼层
上一主题 下一主题
收起左侧

求分一个recursive function的复杂度

🔗
gjy | 只看该作者 |倒序浏览
全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
请问f(x)的复杂是多少?
int f(int x){
if (x<1) return 1;
else return f(x-1)+g(x);
}
int g(int x){
if (x<2) return 2;
else return f(x-1)+g(x/2);
}


上一篇:LeetCode 新题 Two Sum II 求最佳解
下一篇:如何运行刷题的代码?
🔗
zj45499 2015-1-8 12:55:37 | 只看该作者
全局:
本帖最后由 zj45499 于 2015-1-8 13:06 编辑

First rewrite g in terms of f. You get:
  1.     static int g1(int x) {
  2.         if (x < 2) {
  3.             return 2;
  4.         } else {
  5.             return f(x - 1) + f(x/2) -f(x/2-1);
  6.         }
  7.     }
复制代码
Then rewrite f in terms if f. You get:
  1.     static int f1(int x) {
  2.         if (x < 1) {
  3.             return 1;
  4.         } else {
  5.             return 2 * f(x-1) +f(x/2)-f(x/2-1);
  6.         }
  7.     }
复制代码
To calculate a given n, you have to spent twice the time spent on (n-1). This is O(2^n).
the time complexity of f(x / 2) and f(x / 2 - 1) is O(log n).
So O(f(n)) = O(2^n) + O(log n), Or simply O(2^n).


In my machine,
f(19) ~ 3 ms
f(20) ~ 6 ms
f(21) ~ 11 ms
f(22) ~ 23 ms
f(23) ~ 45 ms
f(24) ~ 92 ms
f(25) ~ 186 ms
f(26) ~ 370 ms
f(27) ~ 756 ms
f(28) ~ 1479 ms
f(29) ~ 2952 ms
f(30) ~ 5862 ms
f(31) ~ 12001 ms
...
f(99) ~ STILL RUNNING, should take about 2*10^14 yrs.

This is much too slow.
回复

使用道具 举报

🔗
 楼主| gjy 2015-1-9 03:36:33 | 只看该作者
全局:
真精准!大赞
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表