计算n!
n!=1*2*3*...*n
def Factorial(n):if n <=1:return1return n *Factorial(n-1)
递归的运行方式是递归栈,一层一层的展开,就有点像洋葱“如果你愿意一层一层一层的剥开我的心,你会发现..”,以一个栈的形式一层一层一层的进去然后把它剥开,栈本身在递归调用的时候其内部就给做了一个调用栈
factorial(6)6*factorial(5)6*(5*factorial(4))6*(5*(4*factorial(3)))6*(5*(4*(3*factorial(2))6*(5*(4*(3*(2*factorial(1)))6*(5*(4*(3*(2*1))6*(5*(4*(3*2))6*(5*(4*6)6*(5*24)6*120720
递归代码模板
#Python
def recursion(level,param1,param2,...):
#recursion terminator 递归终结条件,即:递归出口
if level MAX LEVEL:
process_result
return
#process logic in current level 处理当前层的逻辑,该层的业务逻辑代码
process(level,data...)
#drill down 下探到下一层
self.recursion(level + 1,p1,...)
#reverse the current level status if needed 清理当前层
//Java
public void recur(int level,int param){
//terminator
if (level MAX_LEVEL){
//process result
return;
}
//process current logic
process(level,param);
//drill down
recur(level:level + 1,newParam);
//restore current status
}