[leetcode]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?

Note: Given n will be a positive integer.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.

  1. 1 step + 1 step
  2. 2 steps
    Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.

  1. 1 step + 1 step + 1 step
  2. 1 step + 2 steps
  3. 2 steps + 1 step

解法一

思路

要走到第n个阶梯,最后一步只有两种,先走到第n-1个阶梯,然后再走一步,或者先走到第n-2个阶梯,然后再走2步;所以走到第n个阶梯的方法数=走到第n-1个阶梯的方法数+走到第n-2个阶梯的方法数,很明显这是一个递归。时间复杂度接近2的n次方(想象一下递归的树)。但是很不幸,这种方法超时了。。。不过还是写出来。

代码

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

解法二

思路

递归中有太多重复计算的东西,所以我们可以用动态规划的思想,自下而上,进行迭代计算。时间复杂度为O(n),空间复杂度为O(1)。

代码

class Solution {
    public int climbStairs(int n) {
        HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();
        if(n == 1) return 1;
        if(n == 2) return 2;
        int a = 1;
        int b = 2;
        int temp = 0;
        for(int i = 2; i < n; i++){
            temp = a + b;
            a = b;
            b = temp;
        }
        return temp;
    }
}
posted @ 2018-09-30 11:38  shinjia  阅读(134)  评论(0编辑  收藏  举报