爬楼梯
2016-05-16 09:38
363 查看
/*
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?
*/
分析归纳。
f(1) -- s1,=1
f(2) -- s1,s2 =2
f(3) -- s1,s2,s3 =3
f(4) -- s1,s2,s3,s4 =5
f(5) -- s1,s2,s3,s4,s5 =8
...
f(n) -- =f(n-1)+f(n-2)
分析走法,就需要加符号,比如对:s1,s2,s3,s4:
s1,s2,s3,s4
(s1,s2),s3,s4
s1,(s2,s3),s4
s1,s2,(s3,s4)
(s1,s2),(s3,s4)
有且只有5种走法。
最终递推公式:
f(n)= 1, n=1
2, n=2
f(n-1)+f(n-2), n>2
* 方法一:依据递推公式,使用递归的办法。
* 实现简单简洁,但多重的出入栈,性能损耗很大。
* 方法二 :迭代。
* 使用f(n)=f(n-1)+f(n-2)递归,会出现计算超时而通不过评测系统。
* 递归是从大到小(再回去),迭代则从小到大。
* 使用while循环,t = t1+t2,再改变t1跟t2的值,再次循环。循环结束条件i<=n。
// 递归
#include <stdio.h>
int climbStairs(int n) {
if (n == 1) {
return 1;
}
if (n == 2) {
return 2;
}
return climbStairs(n-1) +climbStairs(n-2);
}
int main(int argc, char *argv[])
{
int n = 5;
printf("%d:%d\n", n, climbStairs(n));
return 0;
}
// 迭代
#include <stdio.h>
int climbStairs(int n) {
int t1 = 1;
int t2 = 2;
if (n == 1) {
return t1;
}
else if (n == 2) {
return t2;
}
int t = 0;
int i = 3;
while (i <= n) {
t = t1 + t2;
t1 = t2;
t2 = t;
i ++;
}
return t;
}
int main(int argc, char *argv[])
{
int n = 44;
printf("%d:%d\n", n, climbStairs(n));
return 0;
}
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?
*/
分析归纳。
f(1) -- s1,=1
f(2) -- s1,s2 =2
f(3) -- s1,s2,s3 =3
f(4) -- s1,s2,s3,s4 =5
f(5) -- s1,s2,s3,s4,s5 =8
...
f(n) -- =f(n-1)+f(n-2)
分析走法,就需要加符号,比如对:s1,s2,s3,s4:
s1,s2,s3,s4
(s1,s2),s3,s4
s1,(s2,s3),s4
s1,s2,(s3,s4)
(s1,s2),(s3,s4)
有且只有5种走法。
最终递推公式:
f(n)= 1, n=1
2, n=2
f(n-1)+f(n-2), n>2
* 方法一:依据递推公式,使用递归的办法。
* 实现简单简洁,但多重的出入栈,性能损耗很大。
* 方法二 :迭代。
* 使用f(n)=f(n-1)+f(n-2)递归,会出现计算超时而通不过评测系统。
* 递归是从大到小(再回去),迭代则从小到大。
* 使用while循环,t = t1+t2,再改变t1跟t2的值,再次循环。循环结束条件i<=n。
// 递归
#include <stdio.h>
int climbStairs(int n) {
if (n == 1) {
return 1;
}
if (n == 2) {
return 2;
}
return climbStairs(n-1) +climbStairs(n-2);
}
int main(int argc, char *argv[])
{
int n = 5;
printf("%d:%d\n", n, climbStairs(n));
return 0;
}
// 迭代
#include <stdio.h>
int climbStairs(int n) {
int t1 = 1;
int t2 = 2;
if (n == 1) {
return t1;
}
else if (n == 2) {
return t2;
}
int t = 0;
int i = 3;
while (i <= n) {
t = t1 + t2;
t1 = t2;
t2 = t;
i ++;
}
return t;
}
int main(int argc, char *argv[])
{
int n = 44;
printf("%d:%d\n", n, climbStairs(n));
return 0;
}
相关文章推荐
- android 开发 onRestart()未调用
- angularJS懒加载依赖模块
- xutils使用手册(一)——初始化
- Android_App多语言切换
- PHP PSR-3 日志接口规范 (中文版)
- 【bzoj1602】【Usaco2008 Oct】牧场行走 (暴力) 题解&代码
- [bzoj1601]: [Usaco2008 Oct]灌水牧场行走 最小生成树
- 【Java】内存区域划分
- 堆和栈的区别
- Dumpdecrypted 砸壳失败
- 动态规划1015
- 【第十章】集成其它Web框架 之 10.2 集成Struts1.x ——跟我学spring3
- C#使用System.Data.SQLite操作SQLite
- html5新增的元素与属性
- C#多线程的异步委托/调用
- Struts2_Action访问与Action方法调用
- 通过IMAP方式迁移U-Mail邮件到Exchange 2013之Umail搭建!
- 转:Redis 配置为 Service 系统服务
- [书目20160516]拉姆斯菲尔德规则:美国最高级别的管理课
- HTML 相对路径和绝对路径区别分析(转)