首页 > 其他 > 详细

Pascal's Triangle

时间:2015-01-04 15:19:12      阅读:247      评论: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]
]

Pascal的每一层以1开始和结束 并且自第二位起 其值为其上一层的对角两数之和 用for循环 可以逐步完成此构造 代码如下:

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


Pascal's Triangle

原文:http://blog.csdn.net/u012734829/article/details/42392151

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!