leetCode-Pascal's Triangle
Posted kevincong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetCode-Pascal's Triangle相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章