70. Climbing Stairs

来源:互联网 发布:java idea 编辑:程序博客网 时间:2024/06/16 23:22

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.

这是一道比较简单的动态规划的题目,动态规划最重要的就是要找到将问题的规模变小,并且在规模比较大的时候的计算可以依赖于小规模的时候的结果
首先想办法将题目的规模变小,分析题目的意思可以知道,第N个台阶的到达方法可以有两种从第N-1阶跳一步上去,或者从第N-2阶跳上去,那么这样的话第N阶就有两种方法可以到达,到第N阶的方法就等于到第N-1阶的在加上到第N-2阶的,这样看来这个问题有一种斐波那契数的感觉。
以下是程序:

class Solution {/*这道题目比较巧妙的一点就是利用题目所给出的条件,一次只能走一阶或者两阶所以要到达第N阶可以先到达第N-1阶或者第N-2阶,所以第N阶的步数就是第N-1的步数加上第N-2阶的步数,有一点类似于斐波那契数列的解法*/public:    int climbStairs(int n) {        int i0 = 0;        int i1 = 1;        int i2 = 2;        switch(n) {            case 0:                return 0;            case 1:                return 1;            case 2:                return 2;            default:                int two_before = 1;                int one_before = 2;                int temp = 0;                for (int i = 3; i <= n; i++) {                    temp = one_before;                    one_before += two_before;                    two_before = temp;                }            return one_before;        }    }};

时间复杂度是O(n),空间复杂度是O(1),总的来说还是比较理想的解决方法。

原创粉丝点击