# Solution in Java

• two loops, one go through the row, one go through the column

database: pretty straight forward, ArrayList

calculate element value: K(i)(j)=K(i-1)(j-1)+K(i-1)(j) except for the first and last element

``````public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> triangle = new ArrayList<List<Integer>>();
if (numRows <=0){
return triangle;
}
for (int i=0; i<numRows; i++){
List<Integer> row =  new ArrayList<Integer>();
for (int j=0; j<i+1; j++){
if (j==0 || j==i){
} else {
}
}
}
return triangle;
}
}``````

• This post is deleted!

• This post is deleted!

• The check of numRows <=0 is not necessary.

• public class Solution {
public List<List<Integer>> generate(int numRows) {
if(numRows < 1){
return new ArrayList<List<Integer>>();
}
List<List<Integer>> result = new ArrayList<List<Integer>>(numRows);
List<Integer> lastRow = new ArrayList<Integer>(1);
for(int i=1; i<numRows; i++){
ArrayList<Integer> curRow = new ArrayList<Integer>(i+1);
int j=1;
for(j=1; j<i; j++){
lastRow = result.get(i-1);
}
}
return result;
}
}

• @chennan What is the running time for this solution?

• @acheiver said in Solution in Java:

@chennan What is the running time for this solution?

Thanks for sharing the nice solution.
I have the same question. Could anybody please analyse it? Thanks.

• @acheiver It's clearly n^2...

• in fact, you can save previous `row` to save time.

just like this:

``````public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
ArrayList<Integer> pre = null;
for (int i = 1; i <= numRows; i++) {
ArrayList<Integer> save = new ArrayList<>();
for (int j = 1; j <= i; j++)
if (j == 1 || j == i) save.add(1);
pre = save;
}
return result;
}
}
``````

• Very explicit solution！

• @chennan Brilliant!!! Thanks for sharing.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.