[LeetCode]70. Climbing Stairs

本文介绍经典问题"Climbing Stairs",探讨如何将递归的高时间复杂度优化为动态编程,包括三种解决方案:递归、动态规划数组和仅用两个变量。重点讲解斐波那契数列的应用和优化后的空间与时间复杂度。

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

70. Climbing Stairs

一、题目

Problem Description:
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.

  1. 1 step + 1 step
  2. 2 steps

Example 2:
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.

  1. 1 step + 1 step + 1 step
  2. 1 step + 2 steps
  3. 2 steps + 1 step

Constraints:
1 < = n < = 45 1 <= n <= 45 1<=n<=45

二、题解

  • 爬楼梯问题是一道经典的DP问题
  • 第n个楼梯可以由第n-1楼梯或第n-2个楼梯爬上来
  • 其实这道爬楼问题就是经典的斐波那契数列问题:F(0)=0,F(1)=1, F(n)=F(n - 1)+F(n - 2)
  • 由于题目中n>=0,则初始条件给定F(1)=1,F(2)=2
    解题思路

2.1 Approach #1 : Recursion / Brute Force

注:Wrong:Time Limit Exceeded
以下代码由于时间复杂度过高,无法通过

Time complexity : O ( 2 n ) O(2^n) O(2n). Size of recursion tree will be 2 n 2^n 2n.
Recursion tree for n=5 would be like this:
F(5)

Space complexity : O ( n ) O(n) O(n). The depth of the recursion tree can go upto n n n.

优点:代码简洁明了,可读性高
缺点:如上图二叉树所示,存在大量重复计算

//Recursion / Brute Force
//Time complexity : O(2^n); Space complexity : O(n)
class Solution {
    public int climbStairs(int n) {
		return F(n);
    }
	
	public int F(int n){
		if(n == 1) return 1;
		if(n == 2) return 2;
		return F(n-1) + F(n-2);
	}
}

2.2 Approach #2 : Dynamic Programming

空间换时间:dp[]数组用来存储各个F(n)值

Time complexity : O ( n ) O(n) O(n)
Space complexity : O ( n ) O(n) O(n)

//Dynamic Programming
//Time complexity : O(n); Space complexity : O(n)
class Solution {
    public int climbStairs(int n) {
		if(n == 1) return 1;
		int[] dp = new int[n+1];
		dp[1] = 1;
		dp[2] = 2;
		for(int i = 3; i <= n; i++){
			dp[i] = dp[i-1] + dp[i-2];
		}
		return dp[n]; 
    }
}

2.3 Approach #3 : Optimization of Dynamic Programming

无需dp[]数组,只需两个变量保存F(n-1)和F(n-2)值即可

Time complexity : O ( n ) O(n) O(n)
Space complexity : O ( 1 ) O(1) O(1)

//Dynamic Programming
//Time complexity : O(n); Space complexity : O(1)
class Solution {
    public int climbStairs(int n) {
		if(n == 1) return 1;
		int num2 = 1;//num2表示F(n-2);num2初始化为F(1)=1
		int num1 = 2;//num1表示F(n-1);num1初始化为F(2)=2
		for(int i = 3; i <= n; i++){
			int num = num1 + num2;//num表示F(n);F(n)=F(n-2)+F(n-1)
			num2 = num1;
			num1 = num;
		}
		return num1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值