欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

118. Pascal's Triangle

程序员文章站 2022-04-01 11:31:47
...

Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.
118. Pascal's Triangle


题解:

package com.leetcode;

import java.util.*;

public class PascalTriangle {

    public static void main(String[] args) {
        List<List<Integer>> ans = generate(5);
        for (int i = 0; i < ans.size(); i++) {
            for (int j = 0; j < ans.get(i).size(); j++)
                System.out.print(ans.get(i).get(j) + " ");
            System.out.println();
        }
    }

    public static List<List<Integer>> generate(int numRows) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        for (int i = 1; i <= numRows; i++) {
            if (i == 1) {
                List<Integer> currRow = new ArrayList<Integer>();
                currRow.add(1);
                ans.add(currRow);
            } else if (i == 2) {
                List<Integer> currRow = new ArrayList<Integer>();
                currRow.add(1);
                currRow.add(1);
                ans.add(currRow);
            } else {
                List<Integer> currRow = new ArrayList<Integer>();
                List<Integer> prevRow = ans.get(i - 2);
                for (int j = 0; j < prevRow.size(); j++) {
                    if (j == 0) 
                        currRow.add(1);
                    else
                        currRow.add(prevRow.get(j) + prevRow.get(j - 1));
                }
                currRow.add(1);
                ans.add(currRow);
            }
        }

        return ans;
    }

}
相关标签: Pascal Triangle