Climbing Stairs

来源:互联网 发布:极乐净土动作数据下载 编辑:程序博客网 时间:2024/05/29 03:20

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?

   public int climbStairs(int n) {

    }

Tag:Dynamic Programming

解析:

你在爬楼梯,需要n步到达顶端,每次你可以选择爬一步或者2步,

一共有多少种不同的爬楼梯方式

该问题最关键得到:

如果想计算跑40楼梯的结果,实际等于怕39台阶的结果+爬38台阶的结果。

1,因为当爬到39台阶后,后面只有一种方式爬到40层。

2,当爬到38时,可以选择先爬一步到39,和1重复了,也可以选择直接2步爬到40.

于是就得到了递归运算如下:

    public int climbStairs(int n) {

        if(n==1||n==0) return 1;

        if(n<0) return 0;

        return climbStairs(n-1)+climbStairs(n-2);

    }


不过时间太长,超时了。

使用迭代会节约些时间。

public int climbStairs(int n) {

if (n == 1 || n == 0)

return 1;

int last = 1;

int now = 1;

for (int i = 2; i <= n; i++) {

int temp = last + now;

last = now;

now = temp;

}

return now;

}


0 0