zoukankan      html  css  js  c++  java
  • LeetCode——杨辉三角 i-ii

    Q:给出一个值numRows,生成杨辉三角的前numRows行
    例如,给出 numRows = 5,
    返回
    [↵ [1],↵ [1,1],↵ [1,2,1],↵ [1,3,3,1],↵ [1,4,6,4,1]↵]
    A:

        public static ArrayList<ArrayList<Integer>> generate(int numRows) {
            ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<>();
            if (numRows == 0)
                return arrayLists;
            ArrayList<Integer> array = new ArrayList<>();
            for (int i = 1; i <= numRows; i++) {
                ArrayList<Integer> arrayList = new ArrayList<>();
                for (int j = 0; j < i; j++) {
                    if (j == 0 || j == i - 1)
                        arrayList.add(1);
                    else
                        arrayList.add(array.get(j - 1) + array.get(j));
                }
                array = arrayList;
                arrayLists.add(arrayList);
            }
            return arrayLists;
        }
    

    Q:给出一个索引k,返回杨辉三角的第k行
    例如,k=3,
    返回[1,3,3,1].
    备注:
    你能将你的算法优化到只使用O(k)的额外空间吗?
    A:
    注意,行数是从0开始的。使用从后往前计算。

        public static ArrayList<Integer> getRow(int rowIndex) {
            ArrayList<Integer> array = new ArrayList<>();
            for (int i = 0; i <= rowIndex; i++) {
                for (int j = i - 1; j > 0; j--) {
                    array.set(j, array.get(j) + array.get(j - 1));
                }
                array.add(1);
            }
            return array;
        }
    
  • 相关阅读:
    【BP算法】
    【C++问题整理】
    【最大回文长度】
    【连通区域个数】
    Redis的复制(Master/Slave)、主从复制、读写分离 (下)
    Redis的复制(Master/Slave)、主从复制、读写分离
    Redis发布订阅
    Redis事务
    Redis持久化
    Redis配置文件
  • 原文地址:https://www.cnblogs.com/xym4869/p/12500334.html
Copyright © 2011-2022 走看看