其他分享
首页 > 其他分享> > 118. 杨辉三角

118. 杨辉三角

作者:互联网

 方法1:创建一个数组用来存储数据,然后赋值给list

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> list = new ArrayList<>();
        int [][] ilist= new int[numRows][numRows];
        for(int i=0;i<numRows;i++) {
            List<Integer> slist = new ArrayList<>();
            for (int j = 0; j <= i; j++) {
                if (j == 0 || j == i) {
                    ilist[i][j] = 1;
                } else {
                    ilist[i][j] = ilist[i - 1][j - 1] + ilist[i - 1][j];
                }
                slist.add(ilist[i][j]);
            }
            list.add(slist);
        }
        return list;
    }
}

方法二:

public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> list = new ArrayList<>();
        for(int i=1;i<=numRows;i++){
            List<Integer> sublist = new ArrayList<Integer>();
            sublist.add(1);
            if(i==1){
                list.add(sublist);
                continue;
            }
            for(int j=1;j<i-1;j++){
                List<Integer> temp = list.get(i-2);
                int a = temp.get(j-1);
                int b = temp.get(j);
                sublist.add(a+b);
            }
            sublist.add(1);
            list.add(sublist);
        }
        return list;
    }

创建一个新的list来存储上一行的数据

标签:int,list,sublist,numRows,add,杨辉三角,new,118
来源: https://blog.csdn.net/toutao/article/details/120430773