Skip to content

Commit 0ddb2e5

Browse files
edit 118
1 parent 3a65dc8 commit 0ddb2e5

File tree

1 file changed

+21
-20
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+21
-20
lines changed
Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package com.fishercoder.solutions;
22
import java.util.*;
33

4-
/**Given numRows, generate the first numRows of Pascal's triangle.
4+
/**
5+
* 118. Pascal's Triangle
6+
* Given numRows, generate the first numRows of Pascal's triangle.
57
68
For example, given numRows = 5,
79
Return
@@ -12,30 +14,29 @@
1214
[1,2,1],
1315
[1,3,3,1],
1416
[1,4,6,4,1]
15-
]*/
17+
]
18+
19+
*/
1620
public class _118 {
1721

18-
public static List<List<Integer>> generate(int numRows) {
22+
public List<List<Integer>> generate(int numRows) {
1923
List<List<Integer>> result = new ArrayList();
20-
if(numRows < 1) return result;
21-
List<Integer> row = new ArrayList();
22-
row.add(1);
23-
result.add(row);
24-
for(int i = 1; i < numRows; i++){
25-
List<Integer> newRow = new ArrayList();
26-
newRow.add(1);
27-
List<Integer> lastRow = result.get(i-1);
28-
for(int j = 1; j < lastRow.size(); j++){
29-
newRow.add(lastRow.get(j-1) + lastRow.get(j));
24+
int len = 1;
25+
for (int i = 0; i < numRows; i++) {
26+
List<Integer> row = new ArrayList(len);
27+
row.add(1);
28+
if (i > 0) {
29+
List<Integer> lastRow = result.get(i - 1);
30+
for (int j = 1; j < len; j++) {
31+
if (j < lastRow.size()) {
32+
row.add(lastRow.get(j - 1) + lastRow.get(j));
33+
}
34+
}
35+
row.add(1);
3036
}
31-
newRow.add(1);
32-
result.add(newRow);
37+
result.add(row);
38+
len++;
3339
}
3440
return result;
3541
}
36-
37-
public static void main(String...strings){
38-
int numRows = 2;
39-
generate(numRows);
40-
}
4142
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy