118. Pascal's Triangle
Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
杨辉(帕斯卡)三角
思想是每一行先create一个全是1的数组,然后填充
看似不难,实际上都是细节,比如defensively copying,asList方法的使用,上一行的arraylist是get(i-2)
class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> res = new ArrayList(); if(numRows == 0) return res; res.add(new ArrayList(Arrays.asList(1))); for(int i = 2; i <= numRows; i++){ Integer[] cur = new Integer[i]; Arrays.fill(cur,1); List<Integer> pre = res.get(i-2); for(int j = 1; j < i - 1; j++){ cur[j] = pre.get(j-1) + pre.get(j); } res.add(new ArrayList(Arrays.asList(cur))); } return res; } }
class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> res = new ArrayList(); if(numRows == 0) return res; List<Integer> cur = new ArrayList(Arrays.asList(1)); res.add(new ArrayList(cur)); for(int i = 1; i <= numRows - 1; i++) { for(int j = i - 1; j >= 1; j--) { int tmp = cur.get(j - 1) + cur.get(j); cur.set(j, tmp); } cur.add(1); res.add(new ArrayList(cur)); } return res; } }
class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> res = new ArrayList(); res.add(new ArrayList()); res.get(0).add(1); // res.add(Arrays.asList(new int[]{1})); for(int i = 1; i < numRows; i++) { List<Integer> pre = res.get(i - 1); List<Integer> cur = new ArrayList(); cur.add(1); for(int j = 1; j < i; j++) { cur.add(pre.get(j) + pre.get(j - 1)); } cur.add(1); res.add(cur); } return res; } }