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;
    }
}
相关推荐
j_xxx404_1 分钟前
力扣--分治(快速排序)算法题I:颜色分类,排序数组
数据结构·c++·算法·leetcode·排序算法
阿Y加油吧4 分钟前
力扣打卡day08——轮转数组、除自身外乘积
数据结构·算法·leetcode
Fairy要carry5 分钟前
面试09-Agent 的团队协作
面试·职场和发展
代码探秘者7 分钟前
【算法篇】2.滑动窗口
java·数据结构·后端·python·算法·spring
像素猎人10 分钟前
数组中的二分查找函数:lower_bound【第一个 >= 目标值的元素的值或者下标】 和 upper_bound【第一个 > 目标值的元素的值或者下标】
数据结构·算法
前端摸鱼匠12 分钟前
面试题7:Encoder-only、Decoder-only、Encoder-Decoder三种架构的差异与适用场景?
人工智能·深度学习·ai·面试·职场和发展·架构·transformer
crediks18 分钟前
MTGR(美团生成式推荐框架)总结文档
人工智能·深度学习·算法
im_AMBER18 分钟前
Leetcode 143 搜索插入位置 | 搜索二维矩阵
数据结构·算法·leetcode
小年糕是糕手20 分钟前
【35天从0开始备战蓝桥杯 -- Day5】
数据结构·数据库·c++·算法·蓝桥杯
bbbb36524 分钟前
算法优化的多层缓存映射与访问调度模型的技术7
算法