zoukankan      html  css  js  c++  java
  • [leetcode-118]Pascal's triangle 杨辉三角

    Pascal's triangle

    (1过)

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

    给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

    在杨辉三角中,每个数是它左上方和右上方的数的和。

    示例:

    输入: 5
    输出:
    [
         [1],
        [1,1],
       [1,2,1],
      [1,3,3,1],
     [1,4,6,4,1]
    ]
    public class PascalTriangle {
        public ArrayList<ArrayList<Integer>> generate(int numRows) {
            ArrayList<ArrayList<Integer>> res = new ArrayList<>();
            if (numRows <= 0) {
                return res;
            }
    
            for (int i=0;i<numRows;i++) {
                ArrayList<Integer> list = new ArrayList<>();
                list.add(1);
                for (int j=1;j<=i-1;j++) {
                    list.add(res.get(i-1).get(j-1) + res.get(i-1).get(j));
                }
                if (i>=1) {
                    list.add(1);
                }
                res.add(list);
            }
            return res;
        }
    }

    pascals-triangle-ii

    给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 行。

    在杨辉三角中,每个数是它左上方和右上方的数的和。

    示例:

    输入: 3
    输出: [1,3,3,1]
    

    进阶:

    你可以优化你的算法到 O(k) 空间复杂度吗?

        public ArrayList<Integer> getRow(int rowIndex) {
            ArrayList<Integer> res = new ArrayList<>();
            if (rowIndex < 0) {
                return res;
            }
            res.add(1);
            for (int i=0;i<=rowIndex;i++) {
                // 关键点,从后往前遍历,从前往后的话set(j)会覆盖掉set(j+1)需要的上一行的j
                for (int j=i-1;j>0;j--) {
                    res.set(j,res.get(j-1) + res.get(j));
                }
                if (i>=1) {
                    res.add(1);
                }
            }
            return res;
        }
    }
  • 相关阅读:
    3.4.2内核下的I2C驱动
    AS3批量替换文件
    文件访问权限
    Windows快捷键
    整数与字符串之间的转换函数
    Windows获取文件大小
    Windows内核对象
    ASCII字符集
    IP协议
    获取真正的进程/线程句柄
  • 原文地址:https://www.cnblogs.com/twoheads/p/10566803.html
Copyright © 2011-2022 走看看