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

leetCode-Pascal's Triangle

时间:2017-11-26 21:03:24      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:amp   rate   arraylist   temp   public   span   class   []   维数   

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()将它转换为链表

leetCode-Pascal's Triangle

标签:amp   rate   arraylist   temp   public   span   class   []   维数   

原文地址:http://www.cnblogs.com/kevincong/p/7900325.html

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