Pascal’s Triangle

Given numRows, generate the first numRows of Pascal’s triangle.

For example, given numRows = 5,
Return

  1. [
  2. [1],
  3. [1,1],
  4. [1,2,1],
  5. [1,3,3,1],
  6. [1,4,6,4,1]
  7. ]

Solution:

  1. public class Solution {
  2. public List<List<Integer>> generate(int numRows) {
  3. List<List<Integer>> res = new ArrayList<List<Integer>>();
  4. for (int i = 0; i < numRows; i++) {
  5. List<Integer> list = new ArrayList<Integer>(Arrays.asList(1));
  6. for (int j = 1; j < i; j++) {
  7. list.add(res.get(i - 1).get(j - 1) + res.get(i - 1).get(j));
  8. }
  9. if (i > 0) list.add(1);
  10. res.add(list);
  11. }
  12. return res;
  13. }
  14. }