Leetcode 70. Climbing Stairs

本文探讨了一个经典的动态规划问题——爬楼梯。该问题要求计算到达楼梯顶部的不同方式数量,每次只能上1阶或2阶。通过分析,我们发现其背后的数学规律即斐波那契数列,并提供了一种高效的非递归解决方案。

摘要生成于 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?

 

分析

 

这个题目是一个计算n层阶梯情况下,走到顶端的路径种数(要求每次只能上1层或者2层阶梯)。 这是一个动态规划的题目:

n = 1 时  ways = 1;

n = 2 时  ways = 2;

n = 3 时  ways = 3;

n = k 时  ways = ways[k-1] + ways[k-2];

 

明显的,这是著名的斐波那契数列问题。有递归和非递归两种方式求解

Solving this problem by recursion ,we will do a lot of same recursion. Example: F(10)=F(9)+F(8); F(9)=F(8)+F(7); we calculate F(8) twice,when n is large,this will increase as a rate of n's exponent.

So a more efficient way to solve this problem is from Bottom to Top. Calculate F(0) ,F(1); then F(2).........

(n >= 3)时,只要保存dp[n-1]和dp[n-2]就够了,没必要保存前面的值

 1 class Solution {
 2 public:
 3     int climbStairs(int n) {
 4         int dp[3],temp;
 5         dp[0] = 0;
 6         dp[1] = 1;
 7         dp[2] = 2;
 8         if(n <= 2)
 9             return dp[n];
10         for(int i = 3; i <= n; i++){
11             temp = dp[1] + dp[2];
12             dp[1] = dp[2];
13             dp[2] = temp;
14         }
15         return dp[2];
16     }
17 };

 

转载于:https://www.cnblogs.com/qinduanyinghua/p/5732911.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值