The topic is from LeetCode
Other solutions or source code can be accessed: tongji4m3
description
Suppose you are climbing stairs. It takes n steps to reach the top of the building.
You can climb 1 or 2 steps each time. How many different ways do you have to climb to the top of a building?
Note: Given n is a positive integer.
Example 1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
Example 2:
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶 + 1 阶
Ideas
It’s actually the Fibonacci sequence
Code
public int climbStairs(int n)
{
if(n==1 || n==2) return n;//正整数,不用考虑这么多
int first = 1, second = 2;//初始化为爬1楼,2楼的方法数量
for (int i = 3; i <= n; i++)//i代表楼梯数
{
int temp = first + second;
first = second;
second = temp;
}
return second;
}
Complexity analysis
time complexity
O (N) O (N) O ( N )
Space complexity
O (1) O (1) O ( 1 )