70. Climbing Stairs

来源:互联网 发布:管理业务员的软件 编辑:程序博客网 时间:2024/04/26 13:54

题目:

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?

思路:

这个问题的本质就是一个斐波那契问题,想到这个之后就想用递归来解决。但是后来想到《剑指offer》里面提到递归的方式耗时太长,有时间复杂度更小的解法。


代码如下:

public class Solution {    public int climbStairs(int n) {        //处理特殊情况        if(n < 1){            return 0;        }else if(n == 1){            return 1;        }else if(n == 2){            return 2;        }                int count = 0;        int count1 = 1;        int count2 = 2;        int i;        for(i = 3; i <= n; i++){            count = count1 + count2;            count1 = count2;            count2 = count;        }        return count;    }}

【注】

由于leetcode上面设置的返回值类型时int,因此在这里我设置的变量也是int,不然保险起见个人认为至少定义成long。


0 0
原创粉丝点击