/**
打印效果如下
*
* *
* * *
* *
*
* 根据回溯想到的旧问题的新算法
* @author LeLe
*
*/
public class PrintTriangle {
/**
* 第一次写出的
* @param times
* @param ask
*/
void printA(int times,boolean ask){
for (int i = 5; i > 0; i--) {
if(i<=5-times+1)
System.out.print(" *");
else
System.out.print(" ");
}
System.out.println("");
if(times >1&&ask)
this.printA(times-1,true);
if(ask)
this.printA(times+1,false);
}
/**
* 根据第一次写出进行优化的
* @param times
* @param ask
*/
void printB(int times,boolean ask){
for (int i = 5; i > 0; i--) {
if(i<=5-times+1)
System.out.print(" *");
else
System.out.print(" ");
if(i == 1)
System.out.println("");
if(i==1&×>1&&ask)
this.printB(times -1,true);
if(i==1&&ask)
this.printB(times+1,false);
}
}
public static void main(String[] args){
PrintTriangle p = new PrintTriangle();
long a = System.currentTimeMillis();
p.printB(5,true);
long b = System.currentTimeMillis();
System.out.println("执行时间为 "+(b-a)+"毫秒");
}