青蛙跳阶1小练习
2016-02-28 11:57
274 查看
package cn.itcast.offer1;
/*
* 一只青蛙一次可以跳上1层台阶,也可以跳2层,求该青蛙跳上一个N层的台阶共有多少种跳法
*/
思路分析:
假设青蛙最后一次跳台阶,如果跳1层,则前n-1层有f(n-1)种方法;如果跳2层,则前n-2层有f(n-2)种方法,因此n层台阶共有f(n-1)+f(n-2)=f(n)种跳法;
public class OfferQingwa {
public static void main(String[] args) {
// TODO Auto-generated method stub
int x=method(3);
System.out.println("total="+x);
}
public static int method(int n){
if (n<0){
return -1;
}
else if (n==1){
return 1;
}
else if (n==2){
return 2;
}
else{
return method(n-1)+method(n-2);
}
}
}
/*
* 一只青蛙一次可以跳上1层台阶,也可以跳2层,求该青蛙跳上一个N层的台阶共有多少种跳法
*/
思路分析:
假设青蛙最后一次跳台阶,如果跳1层,则前n-1层有f(n-1)种方法;如果跳2层,则前n-2层有f(n-2)种方法,因此n层台阶共有f(n-1)+f(n-2)=f(n)种跳法;
public class OfferQingwa {
public static void main(String[] args) {
// TODO Auto-generated method stub
int x=method(3);
System.out.println("total="+x);
}
public static int method(int n){
if (n<0){
return -1;
}
else if (n==1){
return 1;
}
else if (n==2){
return 2;
}
else{
return method(n-1)+method(n-2);
}
}
}
相关文章推荐
- U盘加密解密步骤
- 2分钟读懂大数据框架Hadoop和Spark的异同
- maven的目录结构
- Linux进程的查看和调度分别使用什么命令?
- matlab安装配置VLFeat库
- ViewPager 详解(五)-----使用Fragment实现ViewPager滑动
- Clover启动mbr的win7/win8
- 2-9-扩展的线性单链表(带头结点)-线性表-第2章-《数据结构》课本源码-严蔚敏吴伟民版
- 机器学习系列(7)_机器学习路线图(附资料)
- Mac OS X上搭建Apache、PHP、MySQL的Web服务器
- java开发webservice的几种方式(转)
- 字符串和数字的全排列问题、前i位被i整除问题
- PAT (Top Level) Practise 1002 Business (35)
- 容器中swap成员函数
- app自动化的webView页面测试思路(appium工具)。
- “不锈钢”概念
- Dijkstra算法---单源最短路(基础模板)
- Tomcat的安装配置
- leetcode 125: Valid Palindrome
- 正则表达式(一)