您现在的位置是:首页 > 后台技术 > 数据结构与算法数据结构与算法

杨辉三角 II(图文)

第十三双眼睛2023-11-28【数据结构与算法】人已围观

简介杨辉三角 II
给定一个非负索引 rowIndex,返回「杨辉三角」的第 rowIndex 行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。

思路:之前的是返回整个数组,现在是返回指定的一行,其实更容易了,如果是第一行或者第二行,直接写好两个数组返回,如果是3行以上,则需要用上一行的元素进行构建。代码如下:
public static List<Integer> method2(int num) {
    if (num == 0) {
        List<Integer> res = new ArrayList<>();
        res.add(1);
        return res;
    }
    if (num == 1) {
        List<Integer> res = new ArrayList<>();
        res.add(1);
        res.add(1);
        return res;
    }
    List<Integer> tempList = new ArrayList<>();
    List<Integer> resList = new ArrayList<>();
    tempList.add(1);
    tempList.add(1);
    int temp = 2;
    while (temp <= num) {
        resList.add(1);
        for (int i = 1; i < temp; i ++) {
            resList.add(tempList.get(i - 1) + tempList.get(i));
        }
        resList.add(1);
        tempList.clear();
        tempList.addAll(resList);
        resList.clear();
        temp ++;
    }
    return tempList;
}

Tags:

很赞哦! ()

文章评论

    共有条评论来说两句吧...

    用户名:

    验证码:

本站推荐

站点信息

  • 网站名称:JavaStudy
  • 建站时间:2019-1-14
  • 网站程序:帝国CMS7.5
  • 文章统计242篇文章
  • 标签管理标签云
  • 统计数据百度统计
  • 微信公众号:扫描二维码,关注我们