[LeetCode] #118 杨辉三角

给定一个非负整数 numRows生成「杨辉三角」的前 numRows 行。

在「杨辉三角」中,每个数是它左上方和右上方的数的和。

 输入: numRows = 5 输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

根据其性质直接可以直接写出

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        for (int i = 0; i < numRows; i++) {
            List<Integer> row = new ArrayList<Integer>();
            for (int j = 0; j <= i; j++) {
                if (j == 0 || j == i) row.add(1);
                else row.add(res.get(i - 1).get(j - 1) + res.get(i - 1).get(j));
            }
            res.add(row);
        }
        return res;
    }
}

这种解法又称动态规划

知识点:

总结:

复习一下动态规划的概念

动态规划常常适用于有重叠子问题和最优子结构性质的问题.

动态规划相关题目:

[LeetCode] #70 爬楼梯

[LeetCode] #53 最大子序和

posted @ 2021-08-10 13:47  1243741754  阅读(36)  评论(0编辑  收藏  举报