需要帮助找到示例/说明

时间:2014-04-23 20:57:20

标签: recursion

进行一些练习,我的书对说明解决方案没有多大帮助。任何人都可以指出我正确的方向或帮助我剖析这里正在发生的事情吗?

需要递归函数来建模:

当n%2 = 0时,

T(n)= n

当n%2 = 1时,

T(n)= 2 + T(n-1)

谢谢!

2 个答案:

答案 0 :(得分:1)

function T(n) 
{
    if(n%2 == 0) 
        return n;
    else if(n%2 == 1)
        return 2 + T(n-1);
}


So lets say you use 3, then the function enters check 3%2 that's not 0 so it pases to the     else
which now has 3/2 and that returns the following:
function T(3) 
{
    if(n%2 == 0) 
        return n;
    else if(n%2 == 1)
        return 2 + T(n-1); // T(3-1) = T(2)
} 
This here would be equivalent to calling the same function
but now with a 2 instead of a 3 and the return statement would then be added to the 
original 2 and so on, I hope I explained a bit.
function T(2) 
{
    if(n%2 == 0) 
        return n;
    else if(n%2 == 1)
        return 2 + T(n-1);
} 

答案 1 :(得分:1)

这是一个python代码:

def rec(n):
    if n%2 == 0:
        return n;
    else: # if n%2 == 1
        return 2 + rec(n-1)

print(rec(9)) # 10
print(rec(10)) # 10
print(rec(11)) # 12
print(rec(12)) # 12

但问题出在哪里?顺便说一句,它不是真正的递归,因为函数被称为最大一次'递归'。