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;
    }
}
相关推荐
POLITE36 分钟前
Leetcode 234.回文链表 JavaScript (Day 9)
javascript·leetcode·链表
ullio1 小时前
div1+2. 2178F - Conquer or of Forest
算法
Leweslyh1 小时前
制导算法开发实践指南:从入门到精通
算法·开发·武器·制导律设计
chushiyunen1 小时前
快慢双指针算法笔记
数据结构·笔记·算法
烟锁池塘柳02 小时前
一文总结模型压缩技术:剪枝、量化与蒸馏的原理、实践与工程思考
算法·机器学习·剪枝
独自破碎E2 小时前
Leetcode1438绝对值不超过限制的最长连续子数组
java·开发语言·算法
東雪木2 小时前
编程算法学习——数组与排序算法
学习·算法
你撅嘴真丑2 小时前
方格取数 矩阵取数游戏 -动态规划
算法·动态规划
前端小L2 小时前
贪心算法专题(十三):画地为牢的艺术——「划分字母区间」
javascript·算法·贪心算法
@小码农2 小时前
202512 电子学会 Scratch图形化编程等级考试三级真题(附答案)
服务器·开发语言·数据结构·数据库·算法