[LeetCode] 118. Pascal's Triangle

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.


In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example 1:

Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

Input: numRows = 1
Output: [[1]]

Constraints:

  • 1 <= numRows <= 30

杨辉三角。

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

这个三角形注意一下几点

  • 首行只有一个元素 1
  • 每一行的第一个和最后一个元素是 1
  • 中间行的元素个数 = 行的index。注意 index 是从 1 开始的
  • 中间行位于index j 的元素 = 上一行位于 j - 1 的元素 + 上一行位于 j 的元素

时间O(n^2)

空间O(n^2) - list of list

Java实现

 1 class Solution {
 2     public List<List<Integer>> generate(int numRows) {
 3         List<List<Integer>> res = new ArrayList<>();
 4         List<Integer> firstRow = new ArrayList<>();
 5         firstRow.add(1);
 6         res.add(firstRow);
 7         for (int i = 1; i < numRows; i++) {
 8             List<Integer> cur = new ArrayList<>();
 9             // 每一行开头的1
10             cur.add(1);
11             // 从第二个数字开始,都是找上一行的元素
12             // 当前行位置 j 上的数字 = 上一行位置 j - 1 + 上一行位置 j 上的数字
13             for (int j = 1; j < i; j++) {
14                 cur.add(res.get(i - 1).get(j - 1) + res.get(i - 1).get(j));
15             }
16             // 记得加每行最后一个1
17             cur.add(1);
18             res.add(cur);
19         }
20         return res;
21     }
22 }

 

另一种Java实现,有助于版本二

思路是每次先往 list 的头部加一个 1,然后 j 位置是由 j 和 j + 1 位置上的数字的加和决定的,这样就能做到了重复利用 list

 1 class Solution {
 2     public List<List<Integer>> generate(int numRows) {
 3         List<List<Integer>> res = new ArrayList<>();
 4         List<Integer> list = new ArrayList<>();
 5         for (int i = 0; i < numRows; i++) {
 6             list.add(0, 1);
 7             for (int j = 1; j < list.size() - 1; j++) {
 8                 list.set(j, list.get(j) + list.get(j + 1));
 9             }
10             res.add(new ArrayList<>(list));
11         }
12         return res;
13     }
14 }

 

相关题目

118. Pascal's Triangle

119. Pascal's Triangle II

120. Triangle

799. Champagne Tower

2221. Find Triangular Sum of an Array

LeetCode 题目总结

posted @ 2020-05-14 07:25  CNoodle  阅读(526)  评论(0编辑  收藏  举报