试题 算法训练 台阶问题

资源限制

时间限制:1.0s 内存限制:256.0MB

问题描述

  楼梯有N(N<25)级台阶,上楼时一步可以走一级台阶,也可以走二级或三级台阶。请编写一个递归程序,计算共有多少种不同的走法?

样例输入

3

样例输出

4

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();// 台阶数
		System.out.println(f(n));
	}

	public static int f(int n) {
		if (n < 1)
			return 0;
		if (n == 1)
			return 1;
		if (n == 2)
			return 2;
		if (n == 3)
			return 4;
		else {
			return f(n - 1) + f(n - 2) + f(n - 3);
		}
	}
}

试题 算法训练 台阶问题_第1张图片

 

你可能感兴趣的:(蓝桥杯练习,蓝桥杯,java,算法)