码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Pascal's Triangle

时间:2015-05-26 14:27:03      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

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>> list = new ArrayList<List<Integer>>();
    	for (int i = 0; i < numRows; i++) {
    		List<Integer> tmp = new ArrayList<Integer>();
    		if (i == 0) tmp.add(1);
    		else {
    			for (int j = 0; j <= i; j++) {
    				if (j == 0 || j == i) tmp.add(1);
    				else tmp.add(list.get(i-1).get(j) + list.get(i-1).get(j-1));
    			}
    		}
    		
    		list.add(tmp);
    	}
    	
    	return list;
    }
}



LeetCode Pascal's Triangle

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/46006639

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!