70. Climbing Stairs

来源:互联网 发布:python find函数实现 编辑:程序博客网 时间:2024/06/05 15:48

1.Question

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?

2.Code

class Solution {public:    int climbStairs(int n) {        int sum = 0;        for(int i = 0; i <= n; i++)  //i表示走1-step的数目        {            int j = (n - i) / 2;  // j表示走2-step的数目            if(i + j * 2 != n)                continue;            else            {                double numerator = 1, denominator = 1;                for(int k = 0; k < min(i, j); k++)  //根据C(min(i,j),i+j)统计组合可能的情况                {                    denominator *= (1 + k);                    numerator *= (i + j - k);                }                sum += numerator / denominator;            }        }        return sum;    }};
3.Note

a. 这道题思路不难,遍历所有可能的情况,再暴力计数即可。但是遇到了个问题是,关于int, float型 溢出的问题。在计算C(min(i,j), i+j)的时候,对于denominator项( 即阶乘 min(i,j)! )和numerator项,数字小时int型还能容得下,但数字大了以后就会溢出,所以只能选择double型取代int型,甚至float型。

b. 在处理这个溢出问题时,在做题时还想到一个办法,就是先不计算完整的denominator项,为使数字不会一直越乘越大,就利用一个count来保存 denominator/numerator, 如下

                double numerator = 1, denominator = 1, count = 1;                for(int k = 0; k < min(i, j); k++)                {                    denominator = (1 + k);                    numerator = (i + j - k);                    count *= numerator / denominator;                }                sum += count + 0.5;


这里有一个四舍五入的技巧。后来发现这个count没必要。

c. int和float型都是32位,double是64位。以后要在选变量时要考虑溢出问题。

d. 其实对于这道题更正确的看法应该是:这是一道关于斐波那契额数列的问题。所以利用递归可以求解,又因为递归分支太多,则可以利用DP来提高效率。

    int climbStairs(int n) {        vector<int> res(n+1);        res[0] = 1;        res[1] = 1;        for (int i = 2; i <= n; ++i) res[i] = res[i - 1] + res[i - 2];        return res[n];    }




0 0