My 1 ms Java solution.


  • 0
    J
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> prev_line = null;
        for(int i = 0; i < numRows; i++) {
            List<Integer> curr_line = new ArrayList<Integer>();
            for(int j = 0; j < i + 1; j ++) {
                if(j == 0) {
                    curr_line.add(1);
                }
                else if(j == i) {
                    curr_line.add(1);
                }
                else {
                    if(prev_line != null) {
                        curr_line.add(prev_line.get(j - 1) + prev_line.get(j));
                    }
                }
            }
            prev_line = curr_line;
            result.add(curr_line);
        }
        
        return result;
    }

Log in to reply
 

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