118. Pascal's 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]
]

思路:看规律,a[i][j] = a[i-1][j-1]+a[i-1][j] 可以由list.get(i-1).get(j-1)直接实现

public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (numRows<=0) return res;

        for (int i=0;i<numRows;i++){
            List<Integer> row = new ArrayList<Integer>();
            for (int j=0;j<i+1;j++){
                if (j==0||j==i){
                    row.add(1);
                }else{
                    row.add(res.get(i-1).get(j-1)+res.get(i-1).get(j));
                }
            }
            res.add(row);
        }
        return res;
    }
}

results matching ""

    No results matching ""