70. Climbing Stairs

来源:互联网 发布:中国移动java游戏 编辑:程序博客网 时间:2024/06/17 00:14

问题描述

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.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.

  1. 1 step + 1 step
  2. 2 steps

Example 2:

Input: 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

题目链接:


思路分析

给出n阶台阶,一次可以上1阶或者2阶,计算上这n阶台阶有多少种走法。使用动态规划的思想,这就是一个斐波那契数列,将每一步结果放在一个数组中,最后返回结果即可。

代码

class Solution {public:    int climbStairs(int n) {        if (n == 0) return 0;        if (n == 1) return 1;        if (n == 2) return 2;        int sum[n];        sum[0] = 1;sum[1] = 2;        for (int i = 2; i < n; i++){            sum[i] = sum[i-1] + sum[i-2];        }        return sum[n-1];    }};

时间复杂度:O(n)


反思

一开始想到了用DP,但是没有用,还傻乎乎的计算了一下排列组合,还是太麻烦了,斐波那契最好用。

原创粉丝点击