Leetcode: Climbing Stairs

本文探讨了经典的爬楼梯问题,给出了使用动态规划方法解决该问题的两种不同实现方案,并对比了递归与动态规划的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

用了DP的方法,还有hashtable

 1 import java.util.*;
 2 
 3 public class Solution {
 4     public int climbStairs(int n) {
 5         Hashtable<Integer, Integer> table = new Hashtable<Integer, Integer>();
 6         table.put(2, 2);
 7         table.put(1, 1);
 8         table.put(0, 0);
 9         if (n < 0) return 0;
10         return climb(n, table);
11     }
12     
13     public int climb(int n, Hashtable<Integer, Integer> table) {
14         if (table.containsKey(n)) return table.get(n);
15         else {
16             table.put(n, climb(n-1, table) + climb(n-2, table));
17             return table.get(n);
18         }
19     }
20 }

 这道题目是求跑楼梯的可行解法数量。每一步可以爬一格或者两个楼梯,可以发现,递推式是f(n)=f(n-1)+f(n-2),也就是等于前一格的可行数量加上前两格的可行数量。熟悉的朋友可能发现了,这个递归式正是斐波那契数列的定义. 这里base case 是f(1)=1, f(2)=2. Fibonacci是典型的动态规划问题,用Recursion和Iteration都可以,下面列举了Code Ganker写的Iterative解法:

 1 public int climbStairs(int n) {
 2     int f1 = 1;
 3     int f2 = 2;
 4     if(n==1)
 5         return f1;
 6     if(n==2)
 7         return f2;
 8     for(int i=3;i<=n;i++)
 9     {
10         int f3 = f1+f2;
11         f1 = f2;
12         f2 = f3;
13     }
14     return f2;
15 }

用Recursion要小心,比如这种:

 1 public class Solution {
 2     public int climbStairs(int n) {
 3         if (n<=0)
 4         return 0;
 5         if (n==1)
 6         return 1;
 7         if (n==2)
 8         return 2;
 9         return climbStairs(n-1)+climbStairs(n-2);
10     }
11 }

这个递归是指数量级的,n大了会超时~ 你递归还是应该用动态规划来实现~ 也就是要保存历史信息,然后传下去哈~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值