Easy understand Java solution with comments


  • 1
    W
    public static List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new ArrayList<>();
        if (numRows <= 0)
            return result;
        List<Integer> firstLevel = new ArrayList<>();
        firstLevel.add(1);
        result.add(firstLevel); // 第一行初始化后,加入到result中
    
        for (int i = 1; i < numRows; i++) {
            List<Integer> lastLevel = result.get(i - 1); // 指向上一层level
            List<Integer> level = new ArrayList<>();
            level.add(1);
            for (int j = 1; j <= i - 1; j++) {  //[1,i-1]区间
                level.add(lastLevel.get(j - 1) + lastLevel.get(j)); // 上一行相邻两个数之和
            }
            level.add(1);
            result.add(level); // 不要忘记!
        }
        return result;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.