题解 | #蛇形矩阵#
蛇形矩阵
http://www.nowcoder.com/practice/649b210ef44446e3b1cd1be6fa4cab5e
import java.util.*;
public class Main {
public static void main(String[] args) {
/*
蛇形矩阵是由1开始的自然数依次排列成的一个矩阵上三角形。
例如,当输入5时,应该输出的三角形为:
1 3 6 10 15 ||
2 5 9 14 ||
4 8 13 ||
7 12 ||
11 ||
*/
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] arr = new int[n][];
//先给第一行赋值;
arr[0] = new int[n];
int num = 2;
arr[0][0] = 1;
for (int j = 1; j < n; j++) {
arr[0][j] = arr[0][j - 1] + num;
num = num + 1;
}
//从第二行开始给每个一维数组赋值
for (int i = 1; i < n; i++) {
arr[i] = new int[n - i];
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = arr[i - 1][j + 1] - 1;
}
}
for (int i = 0; i < arr.length ; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}