51
51
``` python
52
52
class Solution :
53
53
def generate (self , numRows : int ) -> List[List[int ]]:
54
- res = []
54
+ ans = []
55
55
for i in range (numRows):
56
- t = [1 if j == 0 or j == i else 0 for j in range (i + 1 )]
57
- for j in range (1 , i):
58
- t[j] = res[i - 1 ][j - 1 ] + res[i - 1 ][j]
59
- res.append(t)
60
- return res
56
+ t = [1 if j == 0 or j == i else ans[- 1 ][j] + ans[- 1 ][j - 1 ]
57
+ for j in range (i + 1 )]
58
+ ans.append(t)
59
+ return ans
61
60
```
62
61
63
62
### ** Java**
@@ -67,20 +66,16 @@ class Solution:
67
66
``` java
68
67
class Solution {
69
68
public List<List<Integer > > generate (int numRows ) {
70
- List<List<Integer > > res = new ArrayList<> ();
69
+ List<List<Integer > > ans = new ArrayList<> ();
71
70
for (int i = 0 ; i < numRows; ++ i) {
72
71
List<Integer > t = new ArrayList<> ();
73
72
for (int j = 0 ; j < i + 1 ; ++ j) {
74
- boolean firstOrLast = j == 0 || j == i;
75
- t. add(firstOrLast ? 1 : 0 );
73
+ int v = j == 0 || j == i ? 1 : ans . get(i - 1 ) . get(j) + ans . get(i - 1 ) . get(j - 1 ) ;
74
+ t. add(v );
76
75
}
77
- for (int j = 1 ; j < i; ++ j) {
78
- int val = res. get(i - 1 ). get(j - 1 ) + res. get(i - 1 ). get(j);
79
- t. set(j, val);
80
- }
81
- res. add(t);
76
+ ans. add(t);
82
77
}
83
- return res ;
78
+ return ans ;
84
79
}
85
80
}
86
81
```
@@ -110,17 +105,14 @@ function generate(numRows: number): number[][] {
110
105
class Solution {
111
106
public:
112
107
vector<vector<int >> generate(int numRows) {
113
- vector<vector<int >> res;
114
- for (int i = 0; i < numRows; ++i) {
115
- vector<int > t(i + 1);
116
- t[ 0] = 1;
117
- t[ i] = 1;
118
- for (int j = 1; j < i; ++j) {
119
- t[ j] = res[ i - 1] [ j - 1 ] + res[ i - 1] [ j ] ;
120
- }
121
- res.push_back(t);
108
+ vector<vector<int >> ans;
109
+ for (int i = 0; i < numRows; ++i)
110
+ {
111
+ vector<int > t(i + 1, 1);
112
+ for (int j = 1; j < i; ++j) t[ j] = ans[ i - 1] [ j ] + ans[ i - 1] [ j - 1 ] ;
113
+ ans.push_back(t);
122
114
}
123
- return res ;
115
+ return ans ;
124
116
}
125
117
};
126
118
```
@@ -129,17 +121,16 @@ public:
129
121
130
122
```go
131
123
func generate(numRows int) [][]int {
132
- res := make([][]int, numRows)
133
- for i := 0; i < numRows; i++ {
124
+ ans := make([][]int, numRows)
125
+ for i := range ans {
134
126
t := make([]int, i+1)
135
- t[0] = 1
136
- t[i] = 1
127
+ t[0], t[i] = 1, 1
137
128
for j := 1; j < i; j++ {
138
- t[j] = res [i-1][j-1 ] + res [i-1][j]
129
+ t[j] = ans [i-1][j] + ans [i-1][j-1 ]
139
130
}
140
- res [i] = t
131
+ ans [i] = t
141
132
}
142
- return res
133
+ return ans
143
134
}
144
135
```
145
136
0 commit comments