118.楊輝トライアングル-Java

負でない整数numRowsが与えられた場合、楊輝三角形の最初のnumRows行を生成します。

ここに画像の説明を挿入します
楊慧の三角形では、各数字は左上と右上の数字の合計です。
例:

入力:5
出力:
[
    [1]、
   [1,1]、
  [1,2,1]、
   [1,3,3,1]、
 [1,4,6,4,1]
]

出典:LeetCode
リンク:https://leetcode-cn.com/problems/pascals-triangle

方法:動的計画法

public static List<List<Integer>> generate(int numRows) {
    
    
	List<List<Integer>> lists = new ArrayList<>();
    for (int i = 0; i < numRows; i++) {
    
    
        List<Integer> list = new ArrayList<>();
        for (int j = 0; j <= i; j++) {
    
    
            //第一个位置和最后一个位置的元素为1
            if (j == 0 || j == i) {
    
    
                list.add(1);
            } else {
    
    
                //上一行的元素进行相加
                list.add(lists.get(i - 1).get(j - 1) + lists.get(i - 1).get(j));
            }
        }
        lists.add(list);
    }
    return lists;
}

おすすめ

転載: blog.csdn.net/m0_46390568/article/details/108090686