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;
    }
}
相关推荐
没有钱的钱仔1 小时前
协方差矩阵含义
算法·机器学习·矩阵
垆边人似月.1 小时前
华为机试题 :和为 K 的子数组个数
算法·leetcode·华为
三*一2 小时前
优化修整算法
前端·javascript·算法
达子6662 小时前
RUST 图解 第 3 章:通用编程概念(Common Programming Concepts)
开发语言·算法·rust
夏幻灵2 小时前
每日一题:LeetCode 165:比较版本号
算法·leetcode·职场和发展
道尔柯南2 小时前
C++ 面向对象编程入门:类和对象(上)
开发语言·c++·算法
Navigator_Z2 小时前
LeetCode //C - 1288. Remove Covered Intervals
c语言·算法·leetcode
码爸3 小时前
决策树介绍与示例
python·算法·机器学习
动词ing3 小时前
【题目练习】字符串相乘
算法
0+1114 小时前
算法 --链表
数据结构·算法·leetcode·链表