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;
    }
}
相关推荐
未若君雅裁10 分钟前
LeetCode 51 - N皇后问题 详解笔记
java·数据结构·笔记·算法·leetcode·剪枝
Tim_1039 分钟前
【算法专题训练】30、二叉树的应用
算法
夜晚中的人海40 分钟前
【C++】哈希表算法习题
c++·算法·散列表
Kuo-Teng1 小时前
LeetCode 198: House Robber
java·算法·leetcode·职场和发展·动态规划
2501_941111401 小时前
C++中的状态模式实战
开发语言·c++·算法
SelectDB1 小时前
十亿 JSON 秒级响应:Apache Doris vs ClickHouse,Elasticsearch,PostgreSQL
算法
橘颂TA2 小时前
【剑斩OFFER】算法的暴力美学——除自身以外数组的乘积
算法·leetcode·职场和发展·结构与算法
源码之家2 小时前
机器学习:基于python租房推荐系统 预测算法 协同过滤推荐算法 房源信息 可视化 机器学习-线性回归预测模型 Flask框架(源码+文档)✅
大数据·python·算法·机器学习·数据分析·线性回归·推荐算法
鑫—萍2 小时前
C/C++精品算法——双指针(1)
c语言·c++·算法