# LeetCode – Pascal’s Triangle (Java)

Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, the result should be:

```[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
```

Java Solution

```public ArrayList<ArrayList<Integer>> generate(int numRows) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if (numRows <= 0) return result;   ArrayList<Integer> pre = new ArrayList<Integer>(); pre.add(1); result.add(pre);   for (int i = 2; i <= numRows; i++) { ArrayList<Integer> cur = new ArrayList<Integer>();   cur.add(1); //first for (int j = 0; j < pre.size() - 1; j++) { cur.add(pre.get(j) + pre.get(j + 1)); //middle } cur.add(1);//last   result.add(cur); pre = cur; }   return result; }```
Category >> Algorithms >> Interview
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
```<pre><code>
String foo = "bar";
</code></pre>
```
• Alik Elzin

1+2+3+4+…+n = n(n+1)/2 = ((n^2) + n) / 2
Meaning O(n^2) time.
Space is the same as you create a “memory unit” on each iteration unit.

• Cool!!! This is the solution I was looking for. Thanks for sharing.

• Anish

What is the time and space complexity ?