首页 > 其他 > 详细

Leet Code OJ 118. Pascal's Triangle [Difficulty: Easy]

时间:2016-03-22 12:30:08      阅读:108      评论: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]
]

翻译:
给定一个数numRows,产生前numRows行的杨辉三角(即贾宪三角形、帕斯卡三角形)。

分析:
除了每行首尾是1以外,其他元素均可由上行推出,本方案采用lastLine保存上行数据。

Java版代码:

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

Leet Code OJ 118. Pascal's Triangle [Difficulty: Easy]

原文:http://blog.csdn.net/lnho2015/article/details/50953622

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