1.递归练习
//斐波那契数列
public static long fib(int n){
if(n<0){
throw new IllegalArgumentException("X必须大于等于0 n="+n);
}
if(n==0){
return 0;
}else if(n==1){
return 1;
}else{
return fib(n-1)+fib(n-2);
}
}
//汉诺塔问题,三根柱子abc
public static void hanoi(int n,int from,int to){
if(n<1){
throw new IllegalArgumentException("n 必须大于等于1。n= " +n);
}
if(n==1){
//移动一根柱子的时候,直接移动即可
System.out.printf("直接将1个盘子,从 %d 移动到 %d \n",from,to);
return;
}
int other=(0+1+2)-from-to;//计算other的柱子序号
//将n个柱子从a柱移动到b柱的时候,先将n-1个柱子从a柱移动到c柱
hanoi(n-1,from,other);
//然后将第n个盘子从a柱移动到b柱上
System.out.printf("直接将最底下的1个盘子,从 %d 移动到 %d \n",from,to);
//最后将那n-1个盘子从c柱全部再移动到b柱上去
hanoi(n-1,other,to);
2.递归总结:
哪种形式的问题表现成递归代码
在求解A问题的过程,需要求解一个或者多个同样是A问题,在求解此类问题的时候,不需要进行递归展开,不需要求解通项公式。
3.static总结
语法用法
一共有五个不同的表达: 修改类,修饰方法,修饰属性–static出现在顶级类内部,修饰代码块,用作静态导入。
修饰类、方法、属性、代码块的作用–综合来看,static修饰什么,什么就和对象解绑。
一.修饰属性-属性以对象为单位进行保存。
class person{
String name;
}
person p1=new person(“cpx”);
person p2=new Person(“gb”);
未加static修饰的时候,属性默认存储在P1,P2引用指向的对象中。
class Person{
static int count;
String name;
}
count用static修饰之后,该属性变为静态属性,就不再保存在对象中,而是保存在Person类的内部:具体保存在Person.class这个引用指向的对象(类对象)中。
二.修饰方法–和对象解绑的含义
class Person{
String getName(){…}----可以看作–>static String getName(final Person this){…}
普通方法实际上包含一个指向某个对象的引用,需要有参数,而static方法调用的时候不需要参数;
static int getCount(){…}
}
Person p1=new Person(“cpx”);
p1.getName();--------->Person.getName(p1);
Person.getCount() /p1.getCount();
三.修改类
普通类:
class Outer{
int a;
class Inner{
Outer.this.a;
}
}
Outer outer=new Outer();
Outer.Inner inner=outer.new Inner();
静态类:
class Outer{
int a;
static class inner{不能写为Outer.this.a;}
四.修饰静态代码块
属性初始化:
int a=10;//定义时初始化
{b=20} //构造代码块
Person(){name=…;}//构造方法
执行顺序: 定义时和构造代码块地位平等(先写哪个,先执行哪个) 构造方法的地位较低(无论写在哪,都是最后被执行)
静态属性的初始化(语法位置/初始化顺序)—发生在类被加载的过程中
属性的初始化(语法位置/初始化顺序)----->发生在一个对象被实例化的过程。
而一个类/对象的生命就是 类被加载(仅此一次)----->该类的对象被实例化.
static unt a=10; //变量定义时直接被初始化
static int b;
static{b=20;} //放在静态代码块中被初始化
初始化顺序是按照代码的书写顺序。