要求实现一个杨辉三角,不了解的可以看
public static void main(String[] args) {
int[] arr = new int[]{1};
System.out.println(fn(arr,10));
}
public static int[] fn(int[] array,int n ){
System.out.println(Arrays.toString(array));
if(n==0){
return array;
}
int[] newArray = new int[array.length + 1];
newArray[0] = 1;
newArray[newArray.length-1] = 1;
for(int i=1;i<newArray.length-1;i++){
newArray[i] = array[i]+ array[i-1];
}
return fn(newArray,n-1);
}
运行结果:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
这个怎么居中打印呢? 想要打印成这种种金字塔的样子,可以根据数组的长度计算空格的数量,找出空格的规律,然后根据每一行的数组的大小,计算相应的空格数量,对应的输出就行啦