题目内容
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?
题目分析
我们假设,最后一步完成爬台阶。那么就有两种爬法出现,n-1和n-2两种情况。而完成n步的情况就为,F(n)种,可以推出F(n)=F(n-1)+F(n-2)种。
所以不难发现,递推关系,
F(n)=F(n-1)+F(n-2)
是斐波那契数列。。。。如果发现不了你就记住!!!这个式子是斐波那契数列.
所以解题有两种方式常用的方式,递归,和迭代。
递归一般因为占用空间太大而被抛弃。在leetcode上跑了一下,大概能计算到n=44.
迭代的话,是个正向的过程,直接从n=1开始加,加到n,时间复杂度为 O(n)。
递归
public class Solution {
public int climbStairs(int n) {
int ans=re(n);
return ans;
}
public int re(int n)
{
if(n<1) return n;
int ans=re(n-1)+re(n-2);
return ans;
}
}
迭代
public class Solution {
public int climbStairs(int n) {
int one=0;
int two=1;
int sum=0;
for(int i=0;i<n;i++)
{
sum=one+two;
one =two;
two=sum;
}
return sum;
}
}