題目://假設你現在正在爬樓梯,樓梯有 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 級或者 2 級,那么你有多少種方法爬到樓梯的頂部?//第一行輸入一個整數 n(1≤n≤50),代表樓梯的級數。//輸出爬到樓梯頂部的方法總數。5-->8 3-->3 1-->1 2 -->2
新聞熱點
疑難解答