LeetCode 118. Pascal's Triangle

原题链接在这里:https://leetcode.com/problems/pascals-triangle/

题目:

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

For example, given numRows = 5,
Return

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

题解:

每一行cur都是前一行pre生成出来的,从第三行开始除了首末加"1"外还需要把pre的每两个相邻的和加到cur里。

Time Complexity: O(1 + 2 + 3 + 4... + n) = O(n^2).

Space: O(1), regardless res.

AC Java:

 1 public class Solution {
 2     public List<List<Integer>> generate(int numRows) {
 3         List<List<Integer>> res = new ArrayList<List<Integer>>();
 4         if(numRows == 0){
 5             return res;
 6         }
 7         
 8         List<Integer> pre = new ArrayList<Integer>();
 9         pre.add(1);
10         res.add(pre);
11         
12         for(int i = 0; i<numRows-1; i++){
13             List<Integer> cur = new ArrayList<Integer>();
14             cur.add(1); //首部加第一个1
15             for(int j = 1; j<pre.size(); j++){ 
16                 //第三行才会进入此循环
17                 cur.add(pre.get(j-1) + pre.get(j));
18             }
19             cur.add(1); //末尾加最后一个1
20             res.add(cur);
21             pre = cur;
22         }
23         return res;
24     }
25 }

 跟上一道Pascal's Triangle II

posted @ 2016-01-05 17:01  Dylan_Java_NYC  阅读(777)  评论(0编辑  收藏  举报