题目://假设你现在正在爬楼梯,楼梯有 n级。每次你只能爬 1 级或者 2 级,那么你有多少种方法爬到楼梯的顶部?
//第一行输入一个整数 n(1≤n≤50),代表楼梯的级数。
//输出爬到楼梯顶部的方法总数。5-->8 3-->3 1-->1 2 -->2
package com.sun.DoSubject;
import java.util.Scanner;
//假设你现在正在爬楼梯,楼梯有 n级。每次你只能爬 1 级或者 2 级,那么你有多少种方法爬到楼梯的顶部?
//第一行输入一个整数 n(1≤n≤50),代表楼梯的级数。
//输出爬到楼梯顶部的方法总数。5-->8 3-->3 1-->1 2 -->2
//分析:最后一次爬只有两种情况,不是1级 就是2级,即Method(n) = Method(n-1)+Method(n-2)
public class ClimbStairs {
@SuppressWarnings("resource")
public static void main(String[] args) {
ClimbStairs c = new ClimbStairs();
Scanner s = new Scanner(System.in);
String nextLine = s.nextLine();
int n = Integer.valueOf(nextLine);
System.out.println(c.Method(n));
}
public int Method(int n) {
if (n == 1) {
return 1;
}
if (n == 2) {
return 2;
}
return Method(n - 1) + Method(n - 2);
}
}
//第一行输入一个整数 n(1≤n≤50),代表楼梯的级数。
//输出爬到楼梯顶部的方法总数。5-->8 3-->3 1-->1 2 -->2