【leetcode hot 100 118】杨辉三角

解法一:动态规划

class Solution {
    public List<List<Integer>> generate(int numRows) {
        LinkedList<List<Integer>> result = new LinkedList<>();
        if (numRows == 0) {
            return result;
        }
        for (int i = 0; i < numRows; i++) {
            List<Integer> row = new LinkedList<>();
            if (i == 0) {
                row.add(1);
            }
            else {
                row.add(1); // 第一个数放1
                for (int j = 1; j < i; j++) {
                    // 中间的数等于上面两个数之和
                    row.add(result.get(i - 1).get(j - 1) + result.get(i - 1).get(j));
                }
                row.add(1); // 最后一个数是1
            }
            result.add(row);
        }
        return result;
    }
}

注意:

  • 中间的数等于上面两个数之和,要用j来判断,而不是jfor (int j = 1; j < i; j++)

你可能感兴趣的:(leetcode,算法,职场和发展)