爬台阶问题 —— 递归与动态规划

题目

一个人爬楼梯,他可以一次走一阶或者两阶,输入不同的楼梯数,求有多少种不同的走法?

样例输入

5
8
10

样例输出

8
34
89


三种方法

import java.util.Scanner;

public class Main {
	public static int fun1(int n) {   //递归方法
		if(n == 1 || n==0) {
			return 1;
		}
		return fun1(n-1) + fun1(n-2);
	}
	
	static int f[] = new int[100]; 
	public static int fun2(int n) {  //去重复计算方法  递归
		if(n == 1 || n==0) {
			return 1;
		}
		if(f[n] != 0) {
			return f[n];
		}
		f[n] = fun2(n-1) + fun2(n-2);
		return f[n];
	}
	
	static int f1[] = new int[100];
	public static int fun3(int n) {
		f1[1] = 1;
		f1[0] = 1;
		for(int i = 2; i <= n; i++) {   //递推  动态规划 
			f1[i] = f1[i-1] + f1[i-2];
		}
		return f1[n];
	}
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		
		long start1 = System.currentTimeMillis();
		System.out.println( fun1(n));
		System.out.println(System.currentTimeMillis() - start1);
		
		long start2 = System.currentTimeMillis();
		System.out.println(fun2(n));
		System.out.println(System.currentTimeMillis() - start2);
		
		long start3 = System.currentTimeMillis();
		System.out.println(fun3(n));
		System.out.println(System.currentTimeMillis() - start3);
	}
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值