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 小时前
[AtCoder - abc465_d ]X to Y题解
数据结构·c++·算法
鱼儿也有烦恼1 小时前
数据结构合集
算法·algorithm
兰令水1 小时前
hot100【acm版】【2026.7.11/12打卡-java版本】
java·开发语言·数据结构·算法·职场和发展
研來如此2 小时前
图像文件大小
人工智能·算法·计算机视觉
千纸鹤安安2 小时前
开源 Agent 框架实战:用自然语言替代 Crontab 做运维
算法
从零开始的代码生活_2 小时前
C++ string 详解:常用接口、字符串算法与深拷贝实现
开发语言·c++·后端·学习·算法
Keven_112 小时前
算法札记:差分约束系统为啥叫差分约束系统Σ(っ °Д °;)っ
算法·差分约束系统
XWalnut2 小时前
LeetCode刷题 day29
java·算法·leetcode
embrace_the_sunhaha2 小时前
卡尔曼滤波理解
算法
叩码以求索3 小时前
使用next数组加速匹配过程
java·数据结构·算法