【leetcode】动态规划 - 杨辉三角

题目:
给定一个非负整数 numRows,生成「杨辉三角」的前 numRows 行。

在「杨辉三角」中,每个数是它左上方和右上方的数的和。

示例 1:

输入: numRows = 5
输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

示例 2:

输入: numRows = 1
输出: [[1]]

提示:

1 <= numRows <= 30


思路一:

使用动态规划
而且要明白列表如何使用

动态规划的初始值以及迭代公式,最后的返回值

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res =new ArrayList<List<Integer>>();
        for(int i=0;i<numRows;i++){
            List<Integer> xx= new ArrayList<>();
            for(int j=0;j<=i;j++){
                if(j==0||j==i){
                    xx.add(1);
                }else{
                    xx.add(res.get(i-1).get(j-1)+res.get(i-1).get(j));
                }
            }
            res.add(xx);
        }
        return res;

    }
} 

特别注意这个代码模块

 List<List<Integer>> res =new ArrayList<List<Integer>>();

不可以写成List<List<Integer>> res =new ArrayList<>();

但是这个代码模块

List<Integer> xx= new ArrayList<Integer>();

可以写成List<Integer> xx= new ArrayList<>();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农研究僧

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值