数字塔问题(递归与非递归)
递归方法:
public class Dig5_d
{
final static int M=5;
static void count(int n,int k) //递归方法
{
int i;
if (n==1) //在1前留空
for (i=1;i<=M-k;i++)
System.out.print(" ");
System.out.print(" "+n);
if (n {
count(n+1,k);
System.out.print(" "+n);
}
}
public static void main(String args[])
{
int i;
for (i=1;i<=M;i++)
{
count(1,i);
System.out.println();
}
}
}
非递归:
public class Lianxi2{
public static void main(String args[]){
int a[][]=new int[5][9];
int k=0,i,j;
for(i=0;i<5;i++)
for(j=0;j<9;j++)
a[j]=0;
for(i=0;i<5;i++)
{a[4]=i+1;
k=i;
for(j=0;j a[3-j]=k-j;
a[5+j]=k-j;
}
}
for(i=0;i<5;i++){
for(j=0;j<9;j++)
if(a[j]==0)
System.out.print(" ");
else
System.out.print(a[j]);
System.out.print("\n");
}
}
}
运行结果如下:
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
阅读(1410) | 评论(0) | 转发(0) |