118. Pascal's Triangle

来源:互联网 发布:如何筛选excel数据求和 编辑:程序博客网 时间:2024/06/03 06:01

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]
]
Subscribe to see which companies asked this question

解题思路: 找规律,就是两个for循环计算出值来。比较直接。

public class Solution {    public List<List<Integer>> generate(int numRows) {        List<List<Integer>> res = new ArrayList<List<Integer>>();        if(numRows == 0)        {            return res;        }        ArrayList<Integer> zero = new ArrayList<Integer>();        zero.add(1);        res.add(zero);        for(int i = 1; i < numRows; i++)        {            ArrayList<Integer> vec = new ArrayList<Integer>();            for(int j = 0; j < i+1; j ++)            {                if(j == 0 || j == i)                {                    vec.add(1);                }else                {                    ArrayList<Integer> last = (ArrayList<Integer>)res.get(i-1);                    vec.add(last.get(j) + last.get(j-1));                }            }            res.add(vec);        }        return res;    }}
0 0
原创粉丝点击