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;
    }
}
相关推荐
回敲代码的猴子30 分钟前
2月14日打卡
算法
blackicexs1 小时前
第四周第七天
算法
期末考复习中,蓝桥杯都没时间学了1 小时前
力扣刷题19
算法·leetcode·职场和发展
Renhao-Wan2 小时前
Java 算法实践(四):链表核心题型
java·数据结构·算法·链表
踩坑记录2 小时前
递归回溯本质
leetcode
zmzb01033 小时前
C++课后习题训练记录Day105
开发语言·c++·算法
得一录3 小时前
AI面试·高难度题
人工智能·面试·职场和发展
好学且牛逼的马3 小时前
【Hot100|25-LeetCode 142. 环形链表 II - 完整解法详解】
算法·leetcode·链表
H Corey3 小时前
数据结构与算法:高效编程的核心
java·开发语言·数据结构·算法
programhelp_4 小时前
2026 Adobe面试全流程拆解|OA/VO/Onsite实战指南+高频考点避坑
adobe·面试·职场和发展