119. 杨辉三角

118. 杨辉三角

难度简单354收藏分享切换为英文关注反馈

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

img

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

示例:

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

代码:

class Solution {
    public List<Integer> getRow(int rowIndex) {
       List<Integer> listA = new ArrayList<>();
       List<Integer> listB = new ArrayList<>();

       for(int i=0;i<=rowIndex;i++){
           listB = new ArrayList<>();
           for(int j=0;j<=i;j++){
               if(j==0||j==i){
                   listB.add(1);
               }else{
                   listB.add(listA.get(j - 1) + listA.get(j));
               }
           }

           listA = listB;

       }
       return  listB;
    }

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/pascals-triangle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

posted @ 2020-09-28 20:44  codeFiler  阅读(91)  评论(0编辑  收藏  举报