LeetCode(#118)————杨辉三角形

原文链接:https://github.com/MisterBooo/LeetCodeAnimation/blob/master/notes/LeetCode%E7%AC%AC118%E5%8F%B7%E9%97%AE%E9%A2%98%EF%BC%9A%E6%9D%A8%E8%BE%89%E4%B8%89%E8%A7%92.md

问题描述

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

LeetCode(#118)————杨辉三角形

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

示例:

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

实现方法

class Solution {
    public List<List<Integer>> generate(int numRows) {
        
     List<List<Integer>> result = new ArrayList<>();
     if (numRows < 1) return result;

    for (int i = 0; i < numRows; i++) {
      //扩容
      List<Integer> line = Arrays.asList(new Integer[i+1]);
      
      line.set(0, 1); 
      line.set(i, 1);
      
      for (int j = 1; j < i; j++) {
        //等于上一行的左右两个数字之和
        line.set(j, result.get(i-1).get(j-1) + result.get(i-1).get(j));
      }
      result.add(line);
     }
    return result;   
        
    }
}

代码执行结果:

LeetCode(#118)————杨辉三角形

 

上一篇:AcWing 118. 分形


下一篇:linux uniq命令用法