首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

LeetCode 解題:Pascal's Triangle(楊輝三角)

     編輯:C++ 入門

題目:給定 numRows,生成楊輝三角的前 numRows 行。例如 numRows = 5 時輸出:

[
 [1],
 [1,1],
 [1,2,1],
 [1,3,3,1],
 [1,4,6,4,1]
]

分析與代碼

逐行構造,利用上一行的值計算當前行:首尾為 1,中間元素等於上一行對應位置及其前一位之和。注意邊界條件(numRows <= 0 返回空列表)。

import java.util.ArrayList;
import java.util.List;

public class PascalTriangle {
    public List> generate(int numRows) {
        List> results = new ArrayList<>();
        if (numRows <= 0) return results;
        List firstRow = new ArrayList<>();
        firstRow.add(1);
        results.add(firstRow);
        List lastRow = firstRow;
        for (int i = 1; i < numRows; ++i) {
            List row = new ArrayList<>();
            row.add(1);
            for (int j = 1; j < i; ++j) {
                row.add(lastRow.get(j - 1) + lastRow.get(j));
            }
            row.add(1);
            results.add(row);
            lastRow = row;
        }
        return results;
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved