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;
    }
}
相关推荐
Vacant Seat26 分钟前
贪心算法-跳跃游戏II
算法·游戏·贪心算法
夜松云35 分钟前
从对数变换到深度框架:逻辑回归与交叉熵的数学原理及PyTorch实战
pytorch·算法·逻辑回归·梯度下降·交叉熵·对数变换·sigmoid函数
八股文领域大手子39 分钟前
深入浅出限流算法(三):追求极致精确的滑动日志
开发语言·数据结构·算法·leetcode·mybatis·哈希算法
啊阿狸不会拉杆1 小时前
人工智能数学基础(一):人工智能与数学
人工智能·python·算法
一捌年1 小时前
java排序算法-计数排序
数据结构·算法·排序算法
freexyn2 小时前
Matlab自学笔记五十二:变量名称:检查变量名称是否存在或是否与关键字冲突
人工智能·笔记·算法·matlab
渭雨轻尘_学习计算机ing2 小时前
二叉树构建算法全解析
算法·程序员
蒟蒻小袁3 小时前
力扣面试150题--K 个一组翻转链表
leetcode·链表·面试
C语言魔术师3 小时前
70. 爬楼梯
算法·动态规划
跳跳糖炒酸奶4 小时前
第二章、Isaaclab强化学习包装器(1)
人工智能·python·算法·ubuntu·机器人