溫馨提示×

怎么用java輸出楊輝三角

小億
86
2024-07-27 01:27:08
欄目: 編程語言

下面是一個用Java輸出楊輝三角的示例代碼:

import java.util.*;

public class YangHuiTriangle {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入要輸出的行數(shù):");
        int numRows = sc.nextInt();
        
        List<List<Integer>> triangle = generate(numRows);
        for (List<Integer> row : triangle) {
            for (int num : row) {
                System.out.print(num + " ");
            }
            System.out.println();
        }
    }
    
    public static List<List<Integer>> generate(int numRows) {
        List<List<Integer>> triangle = new ArrayList<>();
        
        if (numRows == 0) {
            return triangle;
        }
        
        List<Integer> firstRow = new ArrayList<>();
        firstRow.add(1);
        triangle.add(firstRow);
        
        for (int i = 1; i < numRows; i++) {
            List<Integer> prevRow = triangle.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);
            
            triangle.add(currRow);
        }
        
        return triangle;
    }
}

運行這段代碼后,輸入要輸出的行數(shù),程序?qū)敵鱿鄳袛?shù)的楊輝三角。

0