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;
    }
}
相关推荐
香芋Yu1 小时前
【大模型面试突击】10_推理部署与优化
面试·职场和发展
蚊子码农1 小时前
算法题解记录--239滑动窗口最大值
数据结构·算法
liliangcsdn1 小时前
A3C算法从目标函数到梯度策略的探索
算法
陈天伟教授2 小时前
人工智能应用- 材料微观:06.GAN 三维重构
人工智能·神经网络·算法·机器学习·重构·推荐算法
liliangcsdn2 小时前
A3C强化学习算法的探索和学习
算法
Figo_Cheung3 小时前
Figo《量子几何学:从希尔伯特空间到全息时空的统一理论体系》(二)
算法·机器学习·几何学·量子计算
额,不知道写啥。3 小时前
HAO的线段树(中(上))
数据结构·c++·算法
LYS_06183 小时前
C++学习(5)(函数 指针 引用)
java·c++·算法
紫陌涵光3 小时前
669. 修剪二叉搜索树
算法·leetcode