118,楊輝三角
阿新 • • 發佈:2018-12-19
給定一個非負整數 numRows,生成楊輝三角的前 numRows 行。
在楊輝三角中,每個數是它左上方和右上方的數的和。
示例:
輸入: 5 輸出: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
思路:用動態規劃
class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> aa=new ArrayList<List<Integer>>(); if(numRows==0) { return aa; } aa.add(new ArrayList<>()); aa.get(0).add(1); for(int i=1;i<numRows;i++) { List<Integer> cur=new ArrayList<>(); List<Integer> pre=aa.get(i-1); cur.add(1); for(int j=1;j<i;j++) { cur.add(pre.get(j-1)+pre.get(j)); } cur.add(1); aa.add(cur); } return aa; } }