鱼C论坛

 找回密码
 立即注册
查看: 2283|回复: 0

[学习笔记] leetcode 118. Pascal's Triangle

[复制链接]
发表于 2019-9-15 08:02:31 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Seawolf 于 2019-9-15 08:50 编辑
  1. Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

  2. PascalTriangleAnimated2.gif

  3. In Pascal's triangle, each number is the sum of the two numbers directly above it.

  4. Example:

  5. Input: 5
  6. Output:
  7. [
  8.      [1],
  9.     [1,1],
  10.    [1,2,1],
  11.   [1,3,3,1],
  12. [1,4,6,4,1]
  13. ]
复制代码

  1. import java.math.BigInteger;
  2. class Solution {
  3.     public List<List<Integer>> generate(int numRows) {
  4.         
  5.         List <List<Integer>> re = new ArrayList<>();
  6.         for(int i = 0; i< numRows; i++){
  7.             
  8.             List <Integer> array = new ArrayList<>();
  9.             
  10.             for(int j = 0; j<= i; j++){
  11.                
  12.                 int num = Integer.parseInt(mul(i-j+1,i).divide(mul(1,j)).toString());
  13.                 array.add(num);
  14.             }
  15.             re.add(array);
  16.             
  17.         }

  18.         return re;
  19.         
  20.     }
  21.    
  22.     public BigInteger mul(int start, int end){
  23.         
  24.         BigInteger sum = BigInteger.ONE;
  25.         
  26.         for(int i = start; i<= end; i++){
  27.             BigInteger num = new BigInteger(String.valueOf(i));
  28.             sum = sum.multiply(num);
  29.         }
  30.         
  31.         return sum;
  32.     }
  33. }
复制代码

  1. class Solution {
  2.     public List<List<Integer>> generate(int numRows) {
  3.         
  4.         List <List<Integer>> re = new ArrayList<>();
  5.         if(numRows == 0) return re;
  6.         List <Integer> array = new ArrayList<>();
  7.         
  8.         array.add(1);
  9.         re.add(array);
  10.         
  11.         for(int i = 1; i < numRows; i++){
  12.             
  13.             List<Integer> pre = re.get(i-1);
  14.             
  15.             List<Integer> cur = new ArrayList<>();
  16.             
  17.             cur.add(1);
  18.             
  19.             for(int j = 1; j < i ; j++){
  20.                
  21.                 cur.add(pre.get(j) + pre.get(j-1));
  22.             }
  23.             
  24.             cur.add(1);
  25.             
  26.             re.add(cur);
  27.         }
  28.         return re;
  29.     }
  30. }
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-13 14:48

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表