1, 题目

给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:

  1. 输入: 3
  2. 输出: [1,3,3,1]

进阶:
你可以优化你的算法到 O(k) 空间复杂度吗?

2, 算法

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