public static int getChoice(int step){
//定义递归的出口
if (step == 1){
return 1;
}
if (step == 2){
return 2;
}
return getChoice(step -1) + getChoice(step - 2);
}
核心在于第十九层只有一种爬法 第十八层也只有一种爬法也就是一次爬俩!
因为18层爬一层楼梯的方法包含在了第19层里面 这就是递归的核心
如果题目改成一次可以爬1、2、3 那么代码应改成:
public static int getChoice(int step){
//定义递归的出口
if (step == 1){
return 1;
}
if (step == 2){
return 2;
}
if (step == 3){
return 4;
}
return getChoice(step -1) + getChoice(step - 2) + getChoice(step - 3);
}
因为第3层楼梯有四种爬法分别是: 111 12 21 3