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 分钟前
L2正则化,防止过拟合-历史补充
算法·过拟合·l2正则化
hansang_IR1 小时前
【题解】LC:Z 算法(Z Algorithm)
c++·算法·字符串
范什么特西1 小时前
回答知识总结02
算法·哈希算法
橘子汽水1681 小时前
Leetcode 230,98:二叉搜索树中第K小的元素,验证二叉搜索树
算法·leetcode·职场和发展
m沐沐1 小时前
【机器学习】DBSCAN聚类算法——原理、参数调优与实战
人工智能·python·深度学习·算法·机器学习·聚类·dbscan
问商十三载1 小时前
GEO优化的6个核心诊断工具,2026年实操版详解
人工智能·算法·机器学习
程序员-Benothing2 小时前
Java ForkJoinPool 详解:从分治思想到高性能并行计算
java·开发语言·后端·面试·职场和发展
手写码匠2 小时前
华为云征文|DeepSeek-R1 智能问数 Agent 实战:Flexus X 实例 + Dify 构建企业级 Text-to-SQL 查询助手
人工智能·深度学习·算法·aigc
mifengxing2 小时前
Java集合与泛型
java·算法·复习笔记
liulilittle2 小时前
[OPENPPP2] ssea 算法详解(中文)
算法·x86·x64·simd·openppp2·ssea·base94