leetCode-Pascal's Triangle

来源:互联网 发布:2017怎么做淘宝客赚钱 编辑:程序博客网 时间:2024/05/29 17:34

Description:
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]]

My Solution:

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

Better Solution:

class Solution {    public List<List<Integer>> generate(int numRows) {        int[][] res = new int[numRows][];        if(numRows == 0)             return (List) Arrays.asList(res);        for(int i = 0; i < numRows; i++){            res[i] = new int[i+1];            for(int j = 0; j < i+1; j++){                if(j == 0 || j == i)                    res[i][j] = 1;                else res[i][j] = res[i-1][j-1] + res[i-1][j];            }        }        return (List) Arrays.asList(res);    }}

总结:利用二维数组,动态增加列的个数,填充元素,然后用Arrays.asList()将它转换为链表

原创粉丝点击