leetcode 118. 杨辉三角

递归:

java 复制代码
class Solution {
    List<List<Integer>> ans = new ArrayList<List<Integer>>();
    int numRows = 0;
    public List<List<Integer>> generate(int numRows) {
        this.numRows = numRows;
        dfs(0);
        return ans;
    }
    private void dfs(int depth) {
        List<Integer> nowA = new ArrayList<Integer>();
        for(int i = 0; i <= depth; i++) { // 不需要单独对边界条件处理
            if(i == 0 || i == depth) {
                nowA.add(1);
                continue;
            }
            nowA.add(ans.get(depth - 1).get(i) + ans.get(depth - 1).get(i - 1));
        }
        ans.add(nowA);
        if (depth + 1 < this.numRows) {
            dfs(depth + 1);
        }
        return;
    }
}

循环的方式实现:

java 复制代码
class Solution {

    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        for(int i = 0; i < numRows; i++) {
            List<Integer> nowA = new ArrayList<Integer>();
            for(int j = 0; j <= i; j++) {
                if (j == 0 || j == i) {
                    nowA.add(1);
                } else {
                    int lastNum = ans.get(i - 1).get(j) + ans.get(i - 1).get(j - 1);
                    nowA.add(lastNum);
                }
            }
            ans.add(nowA);
        }
        return ans;
    }
}
相关推荐
专注仿真1 小时前
问答大模型技术方案算法实现-RAPTOR树构建算法与BEG集成使用
python·算法
zlinear数据采集卡1 小时前
数据采集卡从入门到精通(10):采样率与分辨率的核心关系——反比律、架构分布与过采样
arm开发·嵌入式硬件·算法·fpga开发·架构·开源
GeekZHR3 小时前
C语言指针进阶补充6:动态内存管理、mem系列内存函数、复杂指针声明,一次补齐指针的“三大盲区“
java·c语言·算法·指针
Herbert_hwt3 小时前
第七章 Java深入理解枚举类型
java·开发语言·算法
.道阻且长.3 小时前
8.LeetCode算法习题讲解--滑动窗口--长度最小的子数组
算法·leetcode·职场和发展
(❁´◡`❁)Jimmy(❁´◡`❁)3 小时前
P1156 [USACO01OPEN] 垃圾陷阱
算法·动态规划
疯狂打码的少年3 小时前
【数据结构】二叉排序树(BST)的定义与操作
数据结构·笔记·算法
lally.4 小时前
整数等差数列超图中的三个非微扰现象
算法
wabs6664 小时前
关于字符串【力扣541.反转字符串II的思考】
数据结构·算法·leetcode·字符串
土司大王4 小时前
LeetCode hot100——移动零
java·算法·leetcode