思路:创建一个n*n的矩阵,按照第一层一个数,第二层两个数,第n层n个数依次填充。然后把第2-n列的低层的0移动到高层即可。最后遍历矩阵,打印非零数。
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) { // 注意 while 处理多个 case
int n = in.nextInt();
int arr[][] = new int[n][n];
int count = 0;
for(int i = 0;i<n;++i){
for(int j = 0;j<=i;++j){
arr[j][i] = ++count;
}
}
for(int i = 0 ;i<n;++i){
int zerocount = 0;
int index = 0;
for(int j =0;j<n;++j){
if(arr[i][j]==0){
zerocount++;
}
else arr[i][index++] = arr[i][j];
if(j>=n-zerocount) arr[i][j] = 0;
}
}
for(int i =0;i<n;++i){
for(int j = 0;j<n;++j){
if(arr[i][j]!=0)
System.out.print(arr[j][i]+" ");
else break;
}
System.out.println();
}
}
}
}