递归(6):小白上楼梯

tech2026-08-11  1

题目:

  小白正在上楼梯,楼梯有 n 阶台阶,小白一次可以上1阶,2阶或者3阶。实现一个方法,计算小白有多少种走完楼梯的方式。

代码实现:

import java.util.Scanner; public class _05小白上楼梯 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int res = f(n); System.out.println(res); } private static int f(int n) { if(n == 0)return 1; if(n == 1)return 1; if(n == 2)return 2; return f(n-1)+f(n-2)+f(n-3); } }

运行结果:

最新回复(0)