題目 | Pascal's Triangle |
經過率 | 30.7% |
難度 | Easy |
Given numRows, generate the first numRows of Pascal's triangle.html
For example, given numRows = 5,
Returnjava
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
題目的要求是給定行數輸出Pascal's Triangle,採用集合List進行存儲;
首先要搞清楚Pascal's Triangle的定義與性質 http://www.mathsisfun.com/pascals-triangle.html
下一層的元素是由上一層元素獲得,涉及到相鄰兩項的求和,特別要注意的是最後的鏈表的初始化,以及每行元素開頭和結尾均爲數字1.
java代碼:
public class Solution { public List<List<Integer>> generate(int numRows) { ArrayList<List<Integer>> result = new ArrayList<List<Integer>>(); if(numRows==0) return result; ArrayList<Integer> first = new ArrayList<Integer>(); first.add(1); result.add(first); for(int n=2;n<=numRows;n++){ ArrayList<Integer> thisRow = new ArrayList<Integer>(); //the first element of a new row is one thisRow.add(1); //the middle elements are generated by the values of the previous rows //A(n+1)[i] = A(n)[i - 1] + A(n)[i] List<Integer> preRow = result.get(n-2); for(int i=1;i<n-1;i++){ thisRow.add(preRow.get(i-1)+preRow.get(i)); } //the last element of a new row is also one thisRow.add(1); result.add(thisRow); } return result; } }
2015.1.10this
軟微1420spa