/**
* 递归: n个台阶,可以一次走 1 阶,也可以一次走 2 阶
* 问: 一共有多少种走法
* 注意 : 递归层次很深 有栈溢出风险 且有重复计算问题
*/
public class DiGui {
public int f(int n){
if(n == 1) return 1; // 只剩1阶,有1种走法
if(n == 2) return 2; // 只剩2阶,有2种走法
return f(n-1)+f(n-2);
}
int depth = 0;
Map<Integer,Integer> map = new HashMap(16);
// 防止栈溢出 和 重复计算问题
public int f2(int n){
++ depth;
if(depth > 1000) return -1;
if(n == 1) return 1;
if(n == 2) return 2;
if(map.containsKey(n)){ return map.get(n); }
int res = f(n-1)+f(n-2);
map.put(n,res);
return res;
}
// 非递归修改 防止栈溢出及重复计算问题
public int f3(int n){
int f1 = 1;
int f2 = 2;
int res = 0;
for(int i = 3; i <= n ; i++){
res = f1 + f2;
f1 = f2;
f2 = res;
}
return res;
}
public static void main(String[] args) {
DiGui diGui = new DiGui();
int i = diGui.f3(7);
System.out.println(i);
}
}