leetCode-Pascal's Triangle
阿新 • • 發佈:2017-11-26
asc int color clas class ria gen list() 轉換
Description:
Given numRows, generate the first numRows of Pascal’s triangle.
For example, given numRows = 5,Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
My Solution:
class Solution { public List<List<Integer>> generate(int numRows) { List list= new ArrayList(); for(int i = 1;i <= numRows;i++){ List<Integer> line = new ArrayList<Integer>(); for(int j = 0;j < i;j++){ if(j > 0 &&j < i - 1){ List<Integer>temp = new ArrayList<Integer>(); temp= (ArrayList<Integer>)list.get(list.size() - 1); line.add(temp.get(j - 1) + temp.get(j)); }else{ line.add(1); } } list.add(line); } return list; } }
Better Solution:
class Solution {public List<List<Integer>> generate(int numRows) { int[][] res = new int[numRows][]; if(numRows == 0) return (List) Arrays.asList(res); for(int i = 0; i < numRows; i++){ res[i] = new int[i+1]; for(int j = 0; j < i+1; j++){ if(j == 0 || j == i) res[i][j] = 1; else res[i][j] = res[i-1][j-1] + res[i-1][j]; } } return (List) Arrays.asList(res); } }
總結:利用二維數組,動態增加列的個數,填充元素,然後用Arrays.asList()將它轉換為鏈表
leetCode-Pascal's Triangle