LeetCode 119 杨辉三角II

题目描述:
题目描述


代码一:(就较118题改了参数名和输出)

class Solution {
    
    
    public List<Integer> getRow(int rowIndex) {
    
    
        List<List<Integer>> llist = new ArrayList<List<Integer>>();
        List<Integer> list1 = new ArrayList<Integer>();
        list1.add(1);
        llist.add(list1);
        for(int curRows = 1;curRows <= rowIndex;curRows++){
    
    
            List<Integer> list = new ArrayList<Integer>();
            list.add(1);
            for(int i = 0;i <= curRows - 2;i++){
    
    
                list.add(llist.get(curRows-1).get(i)+llist.get(curRows-1).get(i+1));
            }
            list.add(1);
            llist.add(list);
        }
        return llist.get(rowIndex);
    }
}

结果:

结果

代码二:(只存储前一次和本次list,然后把本次赋给前一次)

class Solution {
    
    
    public List<Integer> getRow(int rowIndex) {
    
    
    List<Integer> list1 = new ArrayList<>();
    List<Integer> list2 = new ArrayList<>();
    for (int i = 0; i <= rowIndex; i++) {
    
    
        list2 = new ArrayList<>();
        for (int j = 0; j <= i; j++) {
    
    
            if (j== 0 || j == i) {
    
    
                list2.add(1);
            } else{
    
    
                list2.add(list1.get(j-1) + list1.get(j));
            } 
        }
        list1 = list2;
    }
    return list2;
}
}

结果:
结果

猜你喜欢

转载自blog.csdn.net/weixin_43752257/article/details/109863549
今日推荐