【LeetCode】Climbing Stairs 解题报告

来源:互联网 发布:电脑超音速录软件 编辑:程序博客网 时间:2024/06/05 04:32

Climbing Stairs

[LeetCode]

https://leetcode.com/problems/climbing-stairs/

Total Accepted: 106510 Total Submissions: 290041 Difficulty: Easy

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?

Ways

注意题目中的意思是,有多少种方法,也就是说加入三个台阶,1,2与2,1是不同的。

方法一

用费布拉奇数列的方法。

为什么呢?因为每次增加一个台阶可以认为是在前面那个解法中任意的一步增加一步。额,我也说不明白。

写出来前面几个数值就能看出来。

1 --> 12 --> 23 --> 34 --> 5……

解法:

public class Solution {    public int climbStairs(int n) {        if(n==1) return 1;        if(n==2) return 2;        return climbStairs(n-1)+climbStairs(n-2);    }}

但是!超时!因为这个方法太慢了,循环次数太多。万万没想到啊!

方法二

LeetCode推荐的动态规划。

参考:http://blog.csdn.net/kenden23/article/details/17377869

动态规划,需要建立一个数组,然后从头开始遍历,在本题中每个位置的结果就是前两个数相加。看最后一个数值就好了。

不是和斐波拉契数列很像嘛?

没想到这个方法算法效率还挺高?

public class Solution {    public int climbStairs(int n) {        int[] counts=new int[n+1];        counts[0]=1;        counts[1]=1;        for(int i=2;i<=n;i++){            counts[i]=counts[i-1]+counts[i-2];        }        return counts[n];    }}

AC:0ms

高手不愧是高手啊,还想到了节省空间。

这个方法只能说牛!三个空间就能完成任务。循环利用就好了。

public class Solution {    public int climbStairs(int n) {        int[] counts=new int[3];        counts[0]=1;        counts[1]=1;        for(int i=2;i<=n;i++){            counts[i%3]=counts[(i-1)%3]+counts[(i-2)%3];        }        return counts[n%3];    }}

AC:0ms

Date

2016/5/1 16:19:44

0 0
原创粉丝点击