Climbing Stairs(70) - easy

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.

Example1:

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

  1. 1 step + 1 step
  2. 2 steps

Example2:

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

思路1:

  • 类似斐波那次数列, 爬n层楼梯的可能的方法为爬n-1层和n-2层楼梯的和.
  • 使用递归完成, 这种代码提交会超时( Time Limit Exceeded)

C++代码:

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

Complexity Analysis:

Time complexity : O( n n n).
Space complexity : O( n n n).


思路2:

  • 改成用循环实现

C++代码:

int climbStairs(int n) {
    if(n <= 0) return 0;
    if(n == 1) return 1;
    if(n == 2) return 2;
    int result;
    int beforeOne = 1,beforeTwo = 2;
    for(int i = 3; i<=n;i++) {
      result = beforeTwo + beforeOne;
      beforeOne = beforeTwo;
      beforeTwo = result;
    }
    return result;
  }

Complexity Analysis:

Time complexity : O( n n n).
Space complexity : O( 1 1 1).


思路3:

  • 使用递归的算法的时候会造成重复计算, 比如, 5层的方法数是计算4层和3层方法数的和, 但是计算4层的方法数时又涉及到计算3层的方法数, 所以该过程存在很多的重复计算.
  • 动态规划来解决, 使用一个表来存储每层的爬楼梯的方法数, 自底向上.

C++代码:

int climbStairs(int n) {
  int table[100];
  table[0] = 1;
  table[1] = 1;
  for(int i = 2; i <= n;i++) {
    table[i] = table[i-1]+table[i-2];
  }
  return table[n];
} 

Complexity Analysis:

Time complexity : O( n n n).
Space complexity : O( n n n).

你可能感兴趣的:(C++,动态规划,Leetcode,Alorithm)