Climbing Stairs
2015-06-10 08:58
387 查看
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?
即求菲波拉契数列,第一次
public int climbStairs(int
n) {
int
ans = 1;
if (n == 1)
return ans;
if (n == 2)
return ans;
ans = climbStairs(n-1) + climbStairs(n-2);
return ans;
}
超时,需要用DP来解决。
public int climbStairs(int
n) {
int
ans = 1;
int current = 1,prev = 2;
if (n == 1)
return current;
if (n == 2)
return prev;
for (int
i = 2; i < n;
i++){
ans =
current + prev;
current =
prev;
prev =
ans;
}
return ans;
}
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
即求菲波拉契数列,第一次
public int climbStairs(int
n) {
int
ans = 1;
if (n == 1)
return ans;
if (n == 2)
return ans;
ans = climbStairs(n-1) + climbStairs(n-2);
return ans;
}
超时,需要用DP来解决。
public int climbStairs(int
n) {
int
ans = 1;
int current = 1,prev = 2;
if (n == 1)
return current;
if (n == 2)
return prev;
for (int
i = 2; i < n;
i++){
ans =
current + prev;
current =
prev;
prev =
ans;
}
return ans;
}
相关文章推荐
- 应用环境下的TIME_WAIT和CLOSE_WAIT处理
- head,tail,cat,more,less
- head,tail,cat,more,less
- DetailCheckoutActivity
- 数据防灾的TurboMail邮件系统部署方案
- IBM X3650 M3 7945XJ9 Raid10 配置
- Add Again(重复元素排序) UVA11076
- There is an overlap in the region chain修复
- There is an overlap in the region chain
- 480000 millis timeout while waiting for channel to be ready for write异常处理
- http://musicbusiness.baijia.baidu.com/article/76737
- Add Again(重复元素排序)
- pip install lxml 报错error: command 'gcc' failed wit
- LightOJ1021---Painful Bases (状压dp)
- LightOJ 1038 - Race to 1 Again 【DP】
- flume-ng负载均衡load-balance、failover集群搭建
- 关于informatica 961Domain库不支持GBK 出现的一系列问题
- HDU1788 Chinese remainder theorem again 最小公倍数
- Container With Most Water——双指针
- LeetCode之“动态规划”:Climbing Stairs