問題
假設你現在正在爬樓梯,樓梯有 n 級。每次你只能爬 1級或者 2級,那麼你有多少種方法爬到樓梯的頂部?
public class ClimbSairs {
public static void main(String[] args) {
System.out.println("爬1個臺階有" + climb(1) + "種走法");
System.out.println("爬2個臺階有" + climb(2) + "種走法");
System.out.println("爬3個臺階有" + climb(3) + "種走法");
System.out.println("爬4個臺階有" + climb(4) + "種走法");
System.out.println("爬5個臺階有" + climb(5) + "種走法");
System.out.println("爬6個臺階有" + climb(6) + "種走法");
}
public static int climb(int n) {
switch (n) {
case 1:
return 1;
case 2:
return 2;
default:
return climb(n - 1) + climb(n - 2);
}
}
}
運行結果:
爬1個臺階有1種走法
爬2個臺階有2種走法
爬3個臺階有3種走法
爬4個臺階有5種走法
爬5個臺階有8種走法
爬6個臺階有13種走法