LeetCode - Climbing Stairs

来源:互联网 发布:rng sky 知乎 编辑:程序博客网 时间:2024/05/18 03:21
 

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 class Test {static int count = 0;public static int climbStairs(int n){if(n > 2){climbStairs(n - 1);climbStairs(n - 2);count = count + 2;}else if(n <= 1){count = count + 1;}return count;}public static void main(String args[]){System.out.println(climbStairs(44));}}


第二次我使用了算法,用了一个数组。因为每一步都是前两步方法的和。AC了。

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



0 0
原创粉丝点击