Climbing Stairs [LEETCODE]

本文探讨了爬楼梯问题的动态规划方法,通过逐步分析和优化,从递归到迭代,实现高效求解路径数量。重点介绍了如何利用动态规划减少时间复杂度,避免重复计算,最终提供了一个更高效的解决方案。

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?

==============================================================

Fisrt, I tried recursive way.

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

But this solution exceed time limit.

So let's think about it. One step has only 1 way , 2 steps have two ways.

Thus N steps have two ways to reach destination: N-1 steps plus one step; N-2 steps plus two steps.

So S[n] = S[n-1] + S[n-2]

Here' s the code:

 1 class Solution {
 2 public:
 3     int climbStairs(int n) {
 4         // Recursively
 5         if(0 == n) return 0;
 6         if(1 == n) return 1;
 7         int *step = new int[n+1];
 8         step[0] = 0;
 9         step[1] = 1;
10         step[2] = 2;
11         for(int i =3; i <=n ; i++){
12             step[i] = step[i-1] + step[i-2];
13         }
14         return step[n];
15     }
16 };

Remind to allocate n+1 space to store steps from 0 to n.

转载于:https://www.cnblogs.com/scenix/p/3368735.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值