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;
    }
}
相关推荐
老鼠只爱大米8 分钟前
LeetCode算法题详解 189:轮转数组
leetcode·轮转数组·数组旋转·环状替换法·算法面试题
葫三生26 分钟前
三生原理范畴语法表明中国哲学可为算法母语
人工智能·深度学习·算法·transformer
D_FW34 分钟前
数据结构第五章:树与二叉树
数据结构·算法
WHS-_-20221 小时前
Tx and Rx IQ Imbalance Compensation for JCAS in 5G NR
javascript·算法·5g
jinmo_C++1 小时前
Leetcode_59. 螺旋矩阵 II
算法·leetcode·矩阵
夏鹏今天学习了吗1 小时前
【LeetCode热题100(81/100)】零钱兑换
算法·leetcode·职场和发展
北京地铁1号线1 小时前
Embedding 模型的经典benchmark:MTEB
算法
焦糖玛奇朵婷1 小时前
盲盒小程序:开发视角下的功能与体验
java·大数据·jvm·算法·小程序
QiZhang | UESTC1 小时前
【豆包生成,写项目看】探寻最优学习路径:线性回归从框架补全到从零手写
学习·算法·线性回归
清 澜2 小时前
大模型扫盲式面试知识复习 (二)
人工智能·面试·职场和发展·大模型