My Simple Solution in 1ms


  • 0
    P

    Two for loops, in each new row, all the element expect first and second are depends on the preceding row adds up two by two.
    Suppose to be O(n^2) time

    public class Solution {
        public List<List<Integer>> generate(int numRows) {
            
            List<List<Integer>> result = new ArrayList<>();
            
            if (numRows < 1){return result;}
    
            for(int i = 0; i < numRows; i++){
                List<Integer> row = new ArrayList<>();
                
                if (i == 0 || result.size() == 0){
                    row.add(1);
                    result.add(row);
                    
                }else{
                    row.add(1);
                    List<Integer> prev = result.get(i - 1);
                    for(int j = 1; j < prev.size(); j++){
                        row.add(prev.get(j) + prev.get(j - 1));
                    }
                    row.add(prev.get(prev.size() - 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.