118. Pascal's Triangle

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

杨辉(帕斯卡)三角
思想是每一行先create一个全是1的数组,然后填充
看似不难,实际上都是细节,比如defensively copying,asList方法的使用,上一行的arraylist是get(i-2)
class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList();
        if(numRows == 0) return res;
        res.add(new ArrayList(Arrays.asList(1)));
        for(int i = 2; i <= numRows; i++){
            Integer[] cur = new Integer[i];
            Arrays.fill(cur,1);
           List<Integer> pre = res.get(i-2);
            for(int j = 1; j < i - 1; j++){
                cur[j] = pre.get(j-1) + pre.get(j);
            }
            res.add(new ArrayList(Arrays.asList(cur)));
        }
        return res;
    }
}
class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList();
        if(numRows == 0) return res;
        List<Integer> cur = new ArrayList(Arrays.asList(1));
        res.add(new ArrayList(cur));
        
        for(int i = 1; i <= numRows - 1; i++) {
            for(int j = i - 1; j >= 1; j--) {
                int tmp = cur.get(j - 1) + cur.get(j);
                cur.set(j, tmp);
            }
            cur.add(1);
            res.add(new ArrayList(cur));
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10495152.html