JAVA - 1ms - just share the code


  • 0
    N
    public class Solution {
        public List<List<Integer>> generate(int numRows) {
            List<List<Integer>> result = new ArrayList<>(numRows);
            
            if (numRows == 0) return result;
            
            result.add(Arrays.asList(1));
            if (numRows == 1) return result;
            
            result.add(Arrays.asList(1, 1));
            if (numRows == 2) return result;
            
            for (int i = 3; i <= numRows; i++) {
                List<Integer> row = new ArrayList<>(i);
                row.add(1);
                
                List<Integer> lastRow = result.get(i-2);
                
                for (int j=1; j < i-1; j++) {
                    row.add(lastRow.get(j) + lastRow.get(j-1));
                }
                
                row.add(1);
                result.add(row);
            }
            return result;
        }
    }
    

Log in to reply
 

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