1, 题目

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

  1. 输入: 5
  2. 输出:
  3. [
  4. [1],
  5. [1,1],
  6. [1,2,1],
  7. [1,3,3,1],
  8. [1,4,6,4,1]
  9. ]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/pascals-triangle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2, 算法

  1. object Solution {
  2. def generate(numRows: Int): List[List[Int]] = {
  3. val buffer = scala.collection.mutable.ListBuffer[List[Int]]()
  4. if (numRows == 0) {
  5. return buffer.toList
  6. }
  7. buffer.append(List(1))
  8. if (numRows == 1) {
  9. return buffer.toList
  10. }
  11. buffer.append(List(1, 1))
  12. if (numRows == 2) {
  13. return buffer.toList
  14. }
  15. var last = Array(1, 1)
  16. for (x <- 3 to numRows) {
  17. val current = scala.collection.mutable.ArrayBuffer[Int]()
  18. current.append(1)
  19. for (i <- Range(0, last.length - 1)) {
  20. current.append(last(i) + last(i + 1))
  21. }
  22. current.append(1)
  23. buffer.append(current.toList)
  24. last = current.toArray
  25. }
  26. buffer.toList
  27. }
  28. }
  1. #python
  2. class Solution:
  3. def generate(self, numRows: int) -> List[List[int]]:
  4. if numRows == 0:
  5. return []
  6. if numRows == 1:
  7. return [[1]]
  8. if numRows == 2:
  9. return [[1], [1, 1]]
  10. result = [[1], [1, 1]]
  11. for x in range(3, numRows + 1):
  12. last = result[-1]
  13. current = [1]
  14. for i in range(len(last) - 1):
  15. current.append(last[i] + last[i + 1])
  16. current.append(1)
  17. result.append(current)
  18. return result