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

Pascal's Triangle

时间:2014-09-09 12:39:28      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   

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) {
        LinkedList<List<Integer>> result=new LinkedList<List<Integer>>();
        if(numRows<1)
        {
            return result;
        }
        List<Integer>p=new LinkedList<Integer>();
        p.add(1);
        result.add(p);
        for(int i=1;i<numRows;i++){
            p=result.get(i-1);
            List<Integer>current=new LinkedList<Integer>();
            current.add(1);
            for(int j=1;j<i;j++)
            {
                current.add(p.get(j-1)+p.get(j));
            }
            current.add(1);
            result.add(current);
        }
        return result;
    }
}


Pascal's Triangle

标签:leetcode   算法   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39153519

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