[LeetCode]题解(python):118 Pascal's Triangle
题目来源
https://leetcode.com/problems/pascals-triangle/
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]
]
题意分析
Input:integer
Output:帕斯卡三角
Conditions:帕斯卡三角数值的规律
题目思路
注意帕斯卡三角中,除了首尾,其他值为上一层的两个邻值的和
AC代码(Python)
1 class Solution(object): 2 def generate(self, numRows): 3 """ 4 :type numRows: int 5 :rtype: List[List[int]] 6 """ 7 ans = [] 8 for i in range(numRows): 9 this = [] 10 for j in range(i+1): 11 this.append(1) 12 if i > 1: 13 for x in range(i - 1): 14 this[x+1] = ans[i-1][x] + ans[i-1][x+1] 15 print this 16 ans.append(this) 17 return ans

浙公网安备 33010602011771号