数据结构与算法分析笔记:第一章:递归

来源:互联网 发布:anaconda linux 下载 编辑:程序博客网 时间:2024/05/16 15:28

一、递归的四条基本法则

        When writing recursive routines, it is crucial to keep in mind the four basic rules of recursion:

1. Base cases.You must always have some base cases, which can be solved without recursion.

2. Making progress.For the cases that are to be solved recursively, the recursive call must alwaysbe to a case that makes progress toward a base case.

3. Design rule.Assume that all the recursive calls work.

4. Compoundinterest rule. Never duplicate work by solving the same instance of aproblem in separate recursive calls.

二、

        可以用递归来求解函数:

        F(0)=0  且 F(X) = 2F(X-1)+X*X,   且X>=0       

int F(int x){if(0 == x)    //line 1return 0;    //line 2elsereturn 2*F(x-1) + x*x;  //line 3}

         可知该函数满足基本法则。

法则1:

        Lines 1 and 2 handle what is known as the base case, that is, the value for which the function is directly known without resorting to recursion.

法则2:

        An important point, however, is that recursive calls will keep on being made until a basecase is reached. For instance, an attempt to evaluatef(-1) will result in calls to f(-2),f(-3), and so on. Since this will never get to a base case, the program won't be able to compute the answer (which is undefined anyway).

         下面这个代码就无法用递归计算,因为它在第三行将Bad(1)定义为Bad(1)。

int Bad(int x){if(0 == x)return 0;elsereturn Bad(x/3+1)+x-1;//line 3}


原创粉丝点击