111. 爬楼梯
假设你正在爬楼梯,需要n步你才能到达顶部。但每次你只能爬一步或者两步,你能有多少种不同的方法爬到楼顶部?
样例
比如n=3,1+1+1=1+2=2+1=3,共有3种不同的方法
返回 3
public class Solution {
/**
* @param n: An integer
* @return: An integer
*/
public int climbStairs(int n) {
// write your code here
if(n<1) return 0;
if(n<3) return n;
int pre=1;
int last=2;
int res=0;
for(int i=2;i<n;i++)
{
res=pre+last;
pre=last;
last=res;
}
return res;
}
}
########################################
class Solution {
public:
/**
* @param n: An integer
* @return: An integer
*/
int climbStairs(int n) {
// write your code here
if(n<1) return 0;
if(n<3) return n;
int last=2;
int pre=1;
int res=0;
for(int i=2;i<n;i++)
{
res=pre+last;
pre=last;
last=res;
}
return res;
}
};
###########################################
class Solution:
"""
@param n: An integer
@return: An integer
"""
def climbStairs(self, n):
# write your code here
if n<1:
return 0
if n<3:
return n
pre=1
last=2
res=0
for i in range(2,n):
res=pre+last
pre=last
last=res
return res