ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Leetcode - 杨辉三角II E[119]

2021-09-14 22:59:50  阅读:151  来源: 互联网

标签:get int List lists II rowIndex 杨辉三角 119


问题描述

给定一个非负索引 rowIndex,返回「杨辉三角」的第 rowIndex 行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
示例 1:
        输入: rowIndex = 3
        输出: [1,3,3,1]
示例 2:
        输入: rowIndex = 0
        输出: [1]
示例 3:
        输入: rowIndex = 1
        输出: [1,1]
提示:
    0 <= rowIndex <= 33

方法1

        根据杨辉三角的规律求出前 rowindex 行,然后返回需要的行。

代码

        public List<Integer> getRow(int rowIndex) {
            List<List<Integer>> lists = new ArrayList<>();
            for(int i = 0;i <= rowIndex;i++){
                List<Integer> aa = new ArrayList<>();
                for(int j = 0;j <= i;j++){
                    if(j == 0 || j == i){
                        aa.add(1);
                        continue;
                    }
                    aa.add(lists.get(i - 1).get(j - 1) + lists.get(i - 1).get(j));
                }
                lists.add(aa);
            }
            return lists.get(rowIndex);
        }

执行结果

 

方法2

        也是根据规律求出前 rowindex 行,然后返回需要的行。但是我们只存储杨辉三角的 一半,在返回的时候对数据进行处理然后返回完整的杨辉三角的一行。

        注意:

                1. 在存储杨辉三角的时候,如何设置每行存储终点下标的设置

                2. array[i - 1][j] 不存在

                3. 还原 返回List 集合 开始还原的下标的设置

代码

        public List<Integer> getRow(int rowIndex) {
            List<List<Integer>> lists = new ArrayList<>();
            for (int i = 0; i <= rowIndex; i++) {
                List<Integer> aa = new ArrayList<>();
                for (int j = 0; j <= i / 2; j++) {
                    if (j == 0) {
                        aa.add(1);
                        continue;
                    }
                    if (lists.get(i - 1).size() < j + 1) {
                        aa.add(lists.get(i - 1).get(j - 1) * 2);
                    } else {
                        aa.add(lists.get(i - 1).get(j - 1) + lists.get(i - 1).get(j));
                    }
                }
                lists.add(aa);
            }
            if (rowIndex > 0) {
                for (int i = (rowIndex + 1) / 2 - 1; i >= 0; i--) {
                    lists.get(rowIndex).add(lists.get(rowIndex).get(i));
                }
                return lists.get(rowIndex);
            }
            return lists.get(0);
        }

执行结果

 

标签:get,int,List,lists,II,rowIndex,杨辉三角,119
来源: https://blog.csdn.net/Lagi_lanumoa/article/details/120298444

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有