鱼C论坛

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

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

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

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

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

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




PascalTriangleAnimated2.gif




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

Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
import java.math.BigInteger;
class Solution {
    public List<List<Integer>> generate(int numRows) {
        
        List <List<Integer>> re = new ArrayList<>();
        for(int i = 0; i< numRows; i++){
            
            List <Integer> array = new ArrayList<>();
            
            for(int j = 0; j<= i; j++){
                
                int num = Integer.parseInt(mul(i-j+1,i).divide(mul(1,j)).toString());
                array.add(num);
            }
            re.add(array);
            
        }

        return re;
        
    }
    
    public BigInteger mul(int start, int end){
        
        BigInteger sum = BigInteger.ONE;
        
        for(int i = start; i<= end; i++){
            BigInteger num = new BigInteger(String.valueOf(i));
            sum = sum.multiply(num);
        }
        
        return sum;
    }
}
class Solution {
    public List<List<Integer>> generate(int numRows) {
        
        List <List<Integer>> re = new ArrayList<>();
        if(numRows == 0) return re;
        List <Integer> array = new ArrayList<>();
        
        array.add(1);
        re.add(array);
        
        for(int i = 1; i < numRows; i++){
            
            List<Integer> pre = re.get(i-1);
            
            List<Integer> cur = new ArrayList<>();
            
            cur.add(1);
            
            for(int j = 1; j < i ; j++){
                
                cur.add(pre.get(j) + pre.get(j-1));
            }
            
            cur.add(1);
            
            re.add(cur);
        }
        return re;
    }
}

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-9-25 22:27

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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