LeetCode OJ-70. Climbing Stairs(爬楼梯问题)

来源:互联网 发布:视频编辑软件 慢动作 编辑:程序博客网 时间:2024/05/22 10:40
70. Climbing Stairs

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?


分治法用递归很容易理解,但超时。直接递推也可以,不过要注意好前一项和前两项的位置。
int climbStairs(int n) {    if (n <= 0) {        return 0;    }        int first = 0;    int second = 1;    int fn;    int i;    for (i = 1; i <= n; ++i) {        fn = first + second;        first = second;        second = fn;    }        return fn;}


0 0
原创粉丝点击