zoukankan      html  css  js  c++  java
  • 每天一道LeetCode--118. Pascal's Triangle(杨辉三角)

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

    solution:

    ackage cn.magicdu;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class _118_Pascal_Triangle {
    
        public List<List<Integer>> generate(int numRows) {
            if (numRows < 0) {
                return null;
            }
            List<List<Integer>> l1 = new ArrayList<>();
            if (numRows >= 1) {
                List<Integer> list = new ArrayList<>();
                list.add(1);
                l1.add(list);
            }
            if (numRows >= 2) {
                List<Integer> list = new ArrayList<>();
                list.add(1);
                list.add(1);
                l1.add(list);
            }
            if (numRows >= 3) {
                for (int i = 3; i <= numRows; i++) {
                    List<Integer> list = new ArrayList<>();
                    List<Integer> prev = l1.get(i - 2);
                    list.add(1);
                    for (int j = 2; j <= i - 1; j++) {
                        list.add(prev.get(j - 2) + prev.get(j - 1));
                    }
                    list.add(1);
                    l1.add(list);
                }
    
            }
    
            return l1;
        }
    
    }
  • 相关阅读:
    使用HSQLDB 客户端(jvm自带数据库使用技巧)
    PageHelper分页
    使用exe4j打包Java程序
    有图形界面的聊天程序
    同时收发消息
    服务端和客户端互聊
    使用Scanner
    收发字符串
    收发数字
    建立连接
  • 原文地址:https://www.cnblogs.com/xiaoduc-org/p/6060897.html
Copyright © 2011-2022 走看看