LeetCode 力扣 118. 楊輝三角

題目描述(簡單難度)

其實就是楊輝三角,當前元素等於上一層的兩個元素的和。

解法一

用兩層循環,注意一下我們下標是從 0 開始還是從 1 開始,然後就可以寫出來了。

public List<List<Integer>> generate(int numRows) {
    List<List<Integer>> ans = new ArrayList<>();
    for (int i = 0; i < numRows; i++) {
        List<Integer> sub = new ArrayList<>();
        for (int j = 0; j <= i; j++) {
            if (j == 0 || j == i) {
                sub.add(1);
            } else {
                List<Integer> last = ans.get(i - 1);
                sub.add(last.get(j - 1) + last.get(j));
            }

        }
        ans.add(sub);
    }
    return ans;
}

好像有一段時間沒有碰到簡單題了,哈哈。

更多詳細通俗題解詳見 leetcode.wang

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章