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;
    }
}
相关推荐
AlunYegeer5 分钟前
面试问题controller和service能不能互相替换
面试·职场和发展
2501_924952696 分钟前
C++模块化编程指南
开发语言·c++·算法
Epiphany.5566 分钟前
题目 3146: 蓝桥杯2023年第十四届省赛真题-网络稳定性 时间限制: 1.5s 内存限制: 256MB
职场和发展·蓝桥杯
qzhqbb6 分钟前
差分隐私与大模型+差分隐私在相关领域应用的论文总结
人工智能·算法
2401_831920749 分钟前
基于C++的爬虫框架
开发语言·c++·算法
我是咸鱼不闲呀10 分钟前
力扣Hot100系列22(Java)——[图论]总结(岛屿数量,腐烂的橘子,课程表,实现Trie(前缀树))
java·leetcode·图论
MSTcheng.16 分钟前
【优选算法必修篇——位运算】『面试题 01.01. 判定字符是否唯一&面试题 17.19. 消失的两个数字』
java·算法·面试
weixin_4219226916 分钟前
模板元编程性能分析
开发语言·c++·算法
2401_8512729919 分钟前
C++中的类型擦除技术
开发语言·c++·算法
Liu6288820 分钟前
C++命名空间使用规范
开发语言·c++·算法