2014木瓜移动校园招聘笔试题之递归优化题解答

来源:互联网 发布:unity3d 头发飘动 编辑:程序博客网 时间:2024/06/11 20:12

在网上看到的,这里给出一个可行解。

原题

代码的优化,给出下一段代码,请做出最好的优化

int f(int n) {    if(n<=4)        return n*n;    else {        return f(n-4)*f(n-1) -f(n-2)*f(n-2);    }}

解答

无非是将递归转化为循环,防止重复计算中间值,跟斐波那契数列f(n)=f(n-1)+f(n-2)一样,解决方式也一样,就是利用几个临时变量保存中间值,然后每次循环都更新临时变量即可。过程没啥好说的,直接给出代码即可。

int f2(int n) {    int first = 1;    int second = 4;    int third = 9;    int fourth = 16;    if(n<=4)        return n*n;    for(int i = 5; i <= n; ++i) {        int tmp = fourth * first - third * third;        first = second;        second = third;        third = fourth;        fourth = tmp;    }    return fourth;}

2 0
原创粉丝点击