用java写一个杨辉三角
时间: 2023-02-20 22:51:21 浏览: 13
基于java的杨辉三角
下面是 Java 代码实现的杨辉三角:
```
import java.util.ArrayList;
import java.util.List;
public class PascalTriangle {
public static void main(String[] args) {
int rows = 5;
List<List<Integer>> result = generate(rows);
for (List<Integer> row : result) {
for (Integer num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
public static List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
if (numRows == 0) {
return result;
}
List<Integer> firstRow = new ArrayList<>();
firstRow.add(1);
result.add(firstRow);
for (int i = 1; i < numRows; i++) {
List<Integer> prevRow = result.get(i - 1);
List<Integer> currRow = new ArrayList<>();
currRow.add(1);
for (int j = 1; j < i; j++) {
currRow.add(prevRow.get(j - 1) + prevRow.get(j));
}
currRow.add(1);
result.add(currRow);
}
return result;
}
}
```
阅读全文