您的位置:首页 > 大数据 > 人工智能

leetcode70-Climbing Stairs

2016-03-09 21:33 477 查看
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增大时,递归结果产生溢出)***/
public class Solution {
public long climbStairs(int n) {
int count=0;
for(int i=0;i<=n/2;i++){
count+=math(n-i)/(math(n-2*i)*math(i));
}
return count;
}
private long math(long j)
{
if(j==0||j==1)
return 1;
else
return j=j*math(j-1);
}
/**方法二:同样递归求解,解决了溢出问题,但运出现运行超时(climbStairs(i)重复计算)**/
public int climbStairs(int n){
if (n == 1 || n == 2) {
return n;
}
return climbStairs(n-1) + climbStairs(n-2);
}

/**方法三:在方法二的基础上做改进,将递归的结果保存至数组中,避免了重复计算的过程**/
if(n==0||n==1||n==2)
{
return n;
}
int []cs=new int[n+1];
cs[0]=0;
cs[1]=1;
cs[2]=2;
for(int i=3;i<=n;i++)
{
cs
=cs[n-1]+cs[n-2];
}
return cs
;
}
}
在写算法的过程中注意时间复杂度和空间复杂度。节省运行时间和内存占用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: