分析
难度 易
来源
https://leetcode.com/problems/pascals-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]
]
解答
1 package LeetCode; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 public class L118_PascalTriangle { 7 public List<List<Integer>> generate(int numRows) { 8 if(numRows<0) 9 return null; 10 List<List<Integer>> result=new ArrayList<List<Integer>>(); 11 List<Integer> list=new ArrayList<Integer>();//记录当前层数值 12 for(int i=0;i<numRows;i++){ 13 list.add(1); 14 for(int j=i-1;j>0;j--){//一行一行赋值,对每行从右向左赋值,避免修改下一个数字要用到两个加数 15 list.set(j,list.get(j-1)+list.get(j)); 16 } 17 result.add(new ArrayList<Integer>(list)); 18 } 19 return result; 20 } 21 public static void main(String[] args){ 22 L118_PascalTriangle l118=new L118_PascalTriangle(); 23 System.out.println(l118.generate(5)); 24 } 25 }