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

思路:

第1,2行没规律。第3行开始除了两边的1中间的数都是由上一行的元素两两相加生成的。

算法:

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


你可能感兴趣的:(【Leetcode】Pascal's Triangle)