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;
    }
}
相关推荐
CoovallyAIHub20 小时前
超越“识别”:下一代机器视觉如何破解具身智能落地难题?
深度学习·算法·计算机视觉
仰泳的熊猫20 小时前
LeetCode:207. 课程表
数据结构·c++·算法·leetcode
liu****20 小时前
19.map和set的封装
开发语言·数据结构·c++·算法
水冗水孚20 小时前
双指针算法在实际开发中的具体应用之代码Review文章字符串的片段分割
算法·leetcode
DuHz20 小时前
用于汽车雷达应用的步进频率PMCW波形——论文阅读
论文阅读·算法·汽车·信息与通信·信号处理·毫米波雷达
张晓~1833994812120 小时前
碰一碰发抖音源码技术搭建部署方案
线性代数·算法·microsoft·矩阵·html5
weixin_4481199420 小时前
Datawhale人工智能的数学基础 202510第3次作业
人工智能·算法
CoovallyAIHub21 小时前
全球OCR新标杆!百度0.9B小模型斩获四项SOTA,读懂复杂文档像人一样自然
深度学习·算法·计算机视觉
weixin_3776348421 小时前
【强化学习】RLMT强制 CoT提升训练效果
人工智能·算法·机器学习
拾光Ծ21 小时前
【C++高阶数据结构】红黑树
数据结构·算法