杨辉三角
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 43411 Accepted Submission(s): 18254
Problem Description
还记得中学时候学过的杨辉三角吗?具体的定义这里不再描述,你可以参考以下的图形:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Input
输入数据包含多个测试实例,每个测试实例的输入只包含一个正整数n(1<=n<=30),表示将要输出的杨辉三角的层数。
Output
对应于每一个输入,请输出相应层数的杨辉三角,每一层的整数之间用一个空格隔开,每一个杨辉三角后面加一个空行。
Sample Input
2 3
Sample Output
1 1 1 1 1 1 1 2 1
Author
lcy
Source
import java.util.Scanner; public class Main { static int[] mat = new int[31]; public static void main(String args[]) { Scanner sc = new Scanner(System.in); mat[0] = 1;// 初始化第一个元素,也就是第一列的值全为1; int n = 0; while (sc.hasNext()) { n = sc.nextInt(); triangle(n); } } public static void triangle(int n) { System.out.println(mat[0]); mat[n - 1] = 1;// 从后面往前面 for (int i = 1; i < n; i++) {// 控制行数 mat[i] = 1; for (int j = i - 1; j > 0; j--) { mat[j] = mat[j] + mat[j - 1]; if (mat[j] < 0) { return; } } for (int j = 0; j <= i; j++) { if (j == 0) { System.out.print(mat[j]); } else { System.out.print(" " + mat[j]); } } System.out.println(); } System.out.println(); } }
时间: 2025-01-12 16:32:30