1. 程式人生 > >LeetCode Pascal's Triangle

LeetCode Pascal's Triangle

Problem

Given numRows, generate the first numRows of Pascal’s triangle.

For example, given numRows = 5, Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

沒記錯的話,這個應該叫楊輝三角型。很簡單的題

Python 實現


'''
Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
'''
# author li.hzh class Solution: def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ if numRows == 0: return [] last_row = [1] result = [last_row] for row in range(2, numRows + 1): cur_row
= [last_row[0]] for i in range(1, len(last_row)): cur_row.append(last_row[i] + last_row[i - 1]) cur_row.append(last_row[len(last_row) - 1]) last_row = cur_row result.append(cur_row) return result

分析

沒什麼可分析的,利用上一層計算出下一層的值即可以。