Climbing Stairs

来源:互联网 发布:hp5200网络打印机驱动 编辑:程序博客网 时间:2024/06/05 09:25

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的问题为T(n)(n >2),则T(n) = T(n-1) + T(n-2)

且T(1) = 1, T(2) = 2

因此程序可如下

class Solution {
public:
    int climbStairs(int n) {
       if (n == 1) return 1;
       if (n == 2) return 2;
       int n_2 = 1, n_1 = 2, n_0 = n_2 + n_1;
       for (int i = 4; i <= n; i++){
           n_2 = n_1;
           n_1 = n_0;
           n_0 = n_1 + n_2;
       }
       return n_0;
    }
};


更简单的,我们只保存两个变量的值,因为T(n) = T(n-1) + T(n-2),所以只需保存T(n-1)和T(n-2),能计算出T(n)就行。下一次就保存T(n-1)和T(n)等等。

令a = T(1), b = T(2),每次迭代可以  a = (b+=a)-a;  即 b = T(3) = a + b, a = T(2) = b-a;

class Solution {
public:
    int climbStairs(int n) {
       if (n == 1) return 1;
       if (n == 2) return 2;
       int a = 1, b = 2;
       for (int i = 3; i <= n; i++)
           a = (b+=a)-a;
       return b;
    }
};

0 0
原创粉丝点击