1. 程式人生 > >LeetCode 118. Pascal's Triangle

LeetCode 118. Pascal's Triangle

分析

題目

Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle. 帕斯卡三角形 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] ]

解答

package LeetCode;

import java.util.ArrayList;
import java.util.List;

public class L118_PascalTriangle {
    public List<List<Integer>> generate(int numRows) {
        List<Integer> curList=new ArrayList<Integer>();
        List<Integer> lastList=new ArrayList<Integer>();
        List<List<Integer>> result=new ArrayList<List<Integer>>();
        for(int i=0;i<numRows;i++){
            for(int j=0;j<=i;j++){
                //curList.add()
                if(j==0)
                    curList.add(1);
                else if(j==i)
                    curList.add(1);
                else
                    curList.add(lastList.get(j-1)+lastList.get(j));
            }
            lastList=curList;
            result.add(lastList);
            curList=new ArrayList<Integer>();
        }
        return result;
    }
    public static void main(String[] args){
        L118_PascalTriangle l118=new L118_PascalTriangle();
        System.out.println(l118.generate(5));
    }
}