题解 | HJ35#蛇形矩阵#
蛇形矩阵
https://www.nowcoder.com/practice/649b210ef44446e3b1cd1be6fa4cab5e
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int anInt = scanner.nextInt(); if (anInt <= 100) { int[][] a = new int[anInt][]; for (int i = 0; i < a.length; i++) { // 给每个一维数组开辟堆内存空间,第n行有n个元素 a[i] = new int[anInt - i]; // 遍历每一个一维数组,赋值 for (int j = 0; j < a[i].length; j++) { // 每一行的第一个元素和最后一个元素都是1 if (j == 0 && i == 0) { a[i][j] = 1; } else if (i == 0) { a[i][j] = a[i][j - 1] + i + j + 1; } else { a[i][j] = a[i - 1][j] + i + j; } } } // 输出杨辉三角 for (int i = 0; i < a.length; i++) { for (int k = 0; k < a[i].length; k++) { System.out.print(a[i][k]+" "); } System.out.println(); } } } }