image.png

解题思路

image.png

  1. class Solution {
  2. public List<List<Integer>> generate(int numRows) {
  3. List<List<Integer>> triangle = new ArrayList<List<Integer>>();
  4. // First base case; if user requests zero rows, they get zero rows.
  5. if (numRows == 0) {
  6. return triangle;
  7. }
  8. // Second base case; first row is always [1].
  9. triangle.add(new ArrayList<>());
  10. triangle.get(0).add(1);
  11. for (int rowNum = 1; rowNum < numRows; rowNum++) {
  12. List<Integer> row = new ArrayList<>();
  13. List<Integer> prevRow = triangle.get(rowNum-1);
  14. // The first row element is always 1.
  15. row.add(1);
  16. // Each triangle element (other than the first and last of each row)
  17. // is equal to the sum of the elements above-and-to-the-left and
  18. // above-and-to-the-right.
  19. for (int j = 1; j < rowNum; j++) {
  20. row.add(prevRow.get(j-1) + prevRow.get(j));
  21. }
  22. // The last row element is always 1.
  23. row.add(1);
  24. triangle.add(row);
  25. }
  26. return triangle;
  27. }
  28. }