LeetCode 34 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]
]
分析:

这道题比较直观,知道杨辉三角的定义就可以了。

public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(numRows == 0) return result;
        for(int i=0; i<numRows; i++){
            List<Integer> row = new ArrayList<Integer>();
            row.add(1);
            if(i > 0){
                for(int j=0; j<result.get(i-1).size()-1; j++)
                    row.add(result.get(i-1).get(j) + result.get(i-1).get(j+1));
                row.add(1);
            }
            result.add(row);    
        }
        return result;
    }
}


你可能感兴趣的:(LeetCode,杨辉三角)