Leetcode 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]
]

解题思路:

用上一次生成的array 生成新的array.


Java code:

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

Reference:

1. http://www.programcreek.com/2014/03/leetcode-pascals-triangle-java/

 

posted @ 2015-10-06 02:47  茜茜的技术空间  阅读(160)  评论(0编辑  收藏  举报