File tree 1 file changed +75
-0
lines changed
1 file changed +75
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
3
+
4
+
5
+ In Pascal's triangle, each number is the sum of the two numbers directly above it.
6
+
7
+ Example:
8
+
9
+ Input: 5
10
+ Output:
11
+ [
12
+ [1],
13
+ [1,1],
14
+ [1,2,1],
15
+ [1,3,3,1],
16
+ [1,4,6,4,1]
17
+ ]
18
+
19
+ 帕斯卡三角。
20
+
21
+ 图看链接:
22
+ https://leetcode.com/problems/pascals-triangle/description/
23
+
24
+ 顺着思路来即可。
25
+
26
+ I
27
+ 测试地址:
28
+ https://leetcode.com/problems/pascals-triangle/description/
29
+
30
+ II
31
+ 测试地址:
32
+ https://leetcode.com/problems/pascals-triangle-ii/description/
33
+
34
+ II 中的要求是返回最后一个,且空间为 O(K)。下面这个空间不是 O(k) 不过只要修改一下即可。
35
+
36
+ """
37
+ # I
38
+ class Solution (object ):
39
+ def generate (self , numRows ):
40
+ """
41
+ :type numRows: int
42
+ :rtype: List[List[int]]
43
+ """
44
+ result = []
45
+
46
+ for i in range (1 , numRows + 1 ):
47
+ x = [0 for j in range (i )]
48
+ x [0 ] = 1
49
+ x [- 1 ] = 1
50
+ for j in range (1 , i - 1 ):
51
+ x [j ] = result [- 1 ][j ] + result [- 1 ][j - 1 ]
52
+
53
+ result .append (x )
54
+
55
+ return result
56
+
57
+ # II
58
+ class Solution (object ):
59
+ def generate (self , numRows ):
60
+ """
61
+ :type numRows: int
62
+ :rtype: List[List[int]]
63
+ """
64
+ result = []
65
+
66
+ for i in range (1 , numRows + 2 ):
67
+ x = [0 for j in range (i )]
68
+ x [0 ] = 1
69
+ x [- 1 ] = 1
70
+ for j in range (1 , i - 1 ):
71
+ x [j ] = result [- 1 ][j ] + result [- 1 ][j - 1 ]
72
+
73
+ result .append (x )
74
+
75
+ return result [- 1 ]
You can’t perform that action at this time.
0 commit comments