70. Climbing Stairs

来源:互联网 发布:js构造函数模式 编辑:程序博客网 时间:2024/05/20 19:29

题目:

  • 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
原创粉丝点击