1 爬楼梯(归纳 f(n)=f(n-1)+f(n-2))
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public class Step { public static void main(String[] args) { Step step = new Step(); int result = step.f(4); System.out.println("result=" + result); } public int f(int n) { if (n == 1 || n == 2) { return n; } else { int result = f(n - 2) + f(n - 1); StringBuilder process = new StringBuilder(); process.append("f(").append(n).append(") = ").append(result).append(" = "); process.append("f(").append(n-2).append(") + f(").append(n-1).append(")"); System.out.println(process.toString()); return result; } } } |
执行结果为
1 2 3 |
f(3) = 3 = f(1) + f(2) f(4) = 5 = f(2) + f(3) result=5 |