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;
    }
}
相关推荐
shehuiyuelaiyuehao4 分钟前
算法29,前缀和,除自身以外的数组的乘积
java·数据结构·算法
智购科技自动售货机厂家8 分钟前
2026自动售货机设备清洁效果自动验证:从图像比对到评分算法的工程实践~YH
人工智能·算法·计算机视觉
姜穆澜38 分钟前
机器学习实战指南:从算法原理到工程落地
人工智能·算法·机器学习
Q一件事1 小时前
RWEQ——保留与消去P的soil_loss联合推导
算法
HugoStudio_SWAN2 小时前
洛谷 P10719 \[GESP202406 五级] 黑白格——暴力美学与图像处理的最小外接矩形
c++·图像处理·人工智能·学习·程序人生·算法·目标跟踪
那年窗外下的雪.2 小时前
AIDC 学习日志|第 20 天|多归属业务验收与哈希不均定位
学习·算法·哈希算法
s_w.h3 小时前
【 刷题 】双指针
算法
啥都想学点的研究生3 小时前
一篇文章讲清楚:K-Means聚类算法
算法·kmeans·聚类
白狐_7984 小时前
408 数据结构|KMP做题方法:next、nextval和高频易错点
数据结构·算法