zoukankan      html  css  js  c++  java
  • leetCode-Pascal's Triangle

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

  • 相关阅读:
    软件工程个人作业02
    第三周学习进度条
    《构建之法》阅读笔记01
    第二周学习进度条
    软件工程个人作业01
    大道至简第三章读后感
    动手动脑课后实践
    JAVA数字想加并输出
    大道至简第二章读后感
    大道至简读后感
  • 原文地址:https://www.cnblogs.com/kevincong/p/7900325.html
Copyright © 2011-2022 走看看