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;
    }
}
相关推荐
我爱cope7 分钟前
【Agent智能体22 | 构建AI工作流的技巧-延迟、成本优化】
人工智能·设计模式·语言模型·职场和发展
装不满的克莱因瓶8 分钟前
了解不同机器学习模型的分类
人工智能·python·算法·机器学习·ai·分类·数据挖掘
QiLinkOS10 分钟前
合肥气链科技有限公司本质总结
c++·科技·算法·gitee·开源
2501_9318037521 分钟前
线性筛(欧拉筛):从原理到应用
算法
酉鬼女又兒23 分钟前
零基础入门计算机网络:MAC地址、IP地址与ARP协议全面解析(含考研真题详解)
网络·网络协议·tcp/ip·计算机网络·考研·macos·职场和发展
ysu_031425 分钟前
leetcode数据结构与算法5~7:链表双指针与二级指针
数据结构·学习·算法·leetcode·链表
小欣加油28 分钟前
leetcode542 01矩阵
数据结构·c++·算法·leetcode·矩阵·bfs
wu_ye_m41 分钟前
学习c语言第34天 用函数每次输出+1,链式访问,int和void
c语言·学习·算法
Felomeng1 小时前
从旧博客出发,向新的世界走去
程序人生·职场和发展
星马梦缘1 小时前
算法设计与分析 作业三 答案与解析
算法·线性规划·二分图匹配·多元最短路·流网络·bellmanford·匈牙利树算法