【LEETCODE】33、LeetCode的Given a non-negative integer numRows, generate the first numRows of Pascal's triangle
package y2019.Algorithm.array; import java.util.ArrayList; import java.util.List; /** * @ProjectName: cutter-point * @Package: y2019.Algorithm.array * @ClassName: Generate * @Author: xiaof * @Description: Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. * Input: 5 * Output: * [ * [1], * [1,1], * [1,2,1], * [1,3,3,1], * [1,4,6,4,1] * ] * * 如果不是第一个数据和最后一个数据,那么中间的数据求值方式 * a[i,j] = a[i - 1][j-1] + a[i - 1][j] * * @Date: 2019/7/1 17:31 * @Version: 1.0 */ public class Generate { //这个效率0ms,已经差不多最快了 public List<List<Integer>> solution(int numRows) { List<List<Integer>> result = new ArrayList<List<Integer>>(); //如果一行都没有,直接反馈空 if(numRows <= 0) { return result; } //遍历生成每一行数据 for(int i = 0; i < numRows; ++i) { //a[i,j] = a[i - 1][j-1] + a[i - 1][j] List row = new ArrayList(); for(int j = 0; j < i + 1; ++j) { //求出每一行的数据 if(j == 0 || j == i) { row.add(1); } else { row.add(result.get(i - 1).get(j - 1) + result.get(i - 1).get(j)); } } result.add(row); } return result; } //大牛答案,内存占用最低,差别再那? public List<List<Integer>> generate(int numRows) { List<List<Integer>> res = new ArrayList<>(); if(numRows==0){ return res; } //这里吧row定义再外面 List<Integer> temp = new ArrayList<>(); temp.add(1); res.add(temp); for (int i = 2; i <= numRows; i++) { try { temp=res.get(i-2); }catch (Exception e){ System.out.println("i = " + i); } //但是这里还是定义了row数据 List<Integer>x=new ArrayList<>(); //也许关键就是这个位置了,再外面+1,少一次循环 x.add(1); for(int j=0;j<temp.size()-1;j++){ x.add(temp.get(j)+temp.get(j+1)); } x.add(1); res.add(x); } return res; } }