70. Climbing Stairs

来源:互联网 发布:c websocket java 编辑:程序博客网 时间:2024/05/21 09:58

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.

这个是典型的斐波拉契数列问题,存在天然的递归结构,可以画出如下递归树分析:

递归+记忆化搜索

class Solution {    vector<int> memo;    int climb(int n){        if (n == 0 || n == 1)            return 1;        if (memo[n] == -1)            memo[n] = climb(n - 1) + climb(n - 2);        return memo[n];    }public:    int climbStairs(int n) {        memo = vector<int>(n + 1, -1);        return climb(n);    }};

动态规划

class Solution {    vector<int> memo;public:    int climbStairs(int n) {        memo = vector<int>(n + 1, -1);        // 初始情况进行设定        memo[0] = 1;        memo[1] = 1;        // 逐步递推求解问题        for (int i = 2; i <= n; i++)            memo[i] = memo[i - 1] + memo[i - 2];        return memo[n];    }};