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;
    }
}
相关推荐
计算机安禾5 分钟前
【数据结构与算法】第12篇:栈(二):链式栈与括号匹配问题
c语言·数据结构·c++·学习·算法·visual studio code·visual studio
散峰而望14 分钟前
【数据结构】单调栈与单调队列深度解析:从模板到实战,一网打尽
开发语言·数据结构·c++·后端·算法·github·推荐算法
qwehjk200816 分钟前
内存泄漏自动检测系统
开发语言·c++·算法
tankeven20 分钟前
HJ153 实现字通配符*
c++·算法
旖-旎22 分钟前
位运算(两整数之和)(3)
c++·算法·leetcode·位运算
酉鬼女又兒23 分钟前
零基础入门前端 第十三届蓝桥杯省赛 :水果拼盘 Flex一篇过(可用于备赛蓝桥杯Web应用开发)
前端·css·职场和发展·蓝桥杯·css3
2301_8166512226 分钟前
C++与Rust交互编程
开发语言·c++·算法
zhaoshuzhaoshu26 分钟前
微内核架构与事件驱动架构的区别与联系详细对比
职场和发展·架构
ab15151729 分钟前
3.28完成9、16、20、98、100、55、57
算法
带娃的IT创业者34 分钟前
营养食谱推荐引擎:基于规则与协同过滤的混合算法
算法·规则引擎·协同过滤·健康管理·食谱推荐·营养搭配·家庭饮食