观察上面有很多方法可以打印出三角形的数字,例如,这里有两种,
// for n=5,
// 1 2 3 4 5
// 6 7 8 9
// 10 11 12
// 13 14
// 15
和
// 5
// 4 9
// 3 8 12
// 2 7 11 14
// 1 6 10 13 15
而且由于递归很有趣!
class triangle
{
//Use recursion,
static int rowUR( int count, int start, int depth )
{
int ndx;
if(count<=0) return start;
//-depth?
for (ndx=0;ndx<depth;ndx++)
{
System.out.print(" ");
}
//how many? 5-depth, 5,4,3,2,1
for( ndx=0; ndx<count; ++ndx )
{
System.out.printf("%3d",start+ndx);
}
System.out.printf("\n");
if( count>0 )
{
rowUR( count-1, ndx+start, depth+1 );
}
return ndx;
}
//Use recursion,
static int rowLR( int count, int start, int depth )
{
int ndx, accum;
if( start < count )
rowLR( count, start+1, depth+1 );
for( ndx=0; ndx<depth; ++ndx )
{
System.out.print(" ");
}
accum=start;
//how many? 5-depth, 1,2,3,4,5
for( ndx=0; ndx<(count-depth); ++ndx )
{
System.out.printf("%3d",accum);
accum+=count-ndx;
}
System.out.printf("\n");
return ndx;
}
public static void main(String[] args)
{
int count=4, depth=0, start=1;
System.out.printf("rowUR\n");
rowUR( count=5, start=1, depth=0 );
System.out.printf("rowLL\n");
rowLL( count=5, start=1, depth=0 );
}
};