首页 > 其他 > 详细

[LeetCode]118 Pascal's Triangle

时间:2015-01-06 18:13:36      阅读:244      评论:0      收藏:0      [点我收藏+]

https://oj.leetcode.com/problems/pascals-triangle/

http://blog.csdn.net/linhuanmars/article/details/23311527

public class Solution {
    public List<List<Integer>> generate(int numRows) {
        
        List<List<Integer>> toReturn = new ArrayList<>();
        if (numRows == 0)
            return toReturn;
        
        List<Integer> firstRow = Collections.<Integer> singletonList(1);
        toReturn.add(firstRow);

        for (int i = 1 ; i < numRows ; i ++)
        {
            List<Integer> lastRow = toReturn.get(toReturn.size() - 1);
            List<Integer> newRow = newRow(lastRow);
            toReturn.add(newRow);
        }

        return toReturn;
    }
    
    private List<Integer> newRow(List<Integer> lastRow)
    {
        int len = lastRow.size() + 1;
        List<Integer> toReturn = new ArrayList<>(len);
        for (int i = 0 ; i < len ; i ++)
        {
            toReturn.add(value(lastRow, i - 1) + value(lastRow , i));
        }
        return toReturn;
    }
    
    private int value(List<Integer> v , int n)
    {
        if (n < 0 || n >= v.size())
            return 0;
        return v.get(n);
    }
}


[LeetCode]118 Pascal's Triangle

原文:http://7371901.blog.51cto.com/7361901/1599797

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