判断递归执行的次数

链接:https://www.nowcoder.com/test/question/done?tid=6762467&qid=1306#summary
来源:牛客网

How many times is f() called when calculating f(10)?
1
2
3
4
5
int f(int x) {
    if(x <= 2)
        return1;
    returnf(x - 2) + f(x - 4) + 1;
}


分析过程如下:

针对这样的题目在别的地方看到的比较好的方法是用树来表示
             10
          8       6
       6    4   4    2
      4  2  2 0 2 0  
    2   0

图中树的节点数是15,所以是调用了15次




范例2:
class program
 {
     static void Main(string[] args)
     {
         int i;
         i = x(x(8));
     }
     static int x(int n)
     {
         if (n <= 3)
             return 1;
         else
             return x(n - 2) + x(n - 4) + 1;
     }
 }
递归算法x(x(8))需要调用几次函数x(int n)?
判断递归执行的次数_第1张图片



你可能感兴趣的:(ACM-2016校招真题)