70. Climbing Stairs

题目:

  • Total Accepted: 166090 
  • Total Submissions: 422448 
  • Difficulty: Easy
  • Contributor: 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?

Note: Given n will be a positive integer.


解题思路:

这题可以被分解为几个子问题,因此可以使用动态规划的方法来解决:

要走到第i级台阶有两种方法:

1. 从第i-1级台阶走1步到达

2. 从第i-2级台阶走2步到达

所以到达第i级台阶的方法数的等于到达第i-1级台阶的方法数和到达第i-2级台阶的方法数之和。

再使用一个数组来记录到达每一级的方法数以避免重复计算。

count[i] = count[i - 1] + count[i - 2]


代码:

class Solution {
public:
    int count[1000];
    int climbStairs(int n) {
        count[1] = 1;
        count[2] = 2;
        for(int i = 3; i <= n; i++){
            count[i] = count[i - 1] + count[i - 2];
        }
        return count[n];
    }
};


分析:

时间复杂度:O(N)

空间复杂度:O(N)

另外还可以使用类似求斐波那契数列的方法,用两个变量来记录上两级台阶的方法数,这样可以将空间复杂度减小到O(1)


Leetcode上面总结了这道题的多种解决方法 https://leetcode.com/articles/climbing-stairs/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值