A simple java solution using reference to previous list


  • 0
    G
    public class Solution {
        public List<List<Integer>> generate(int numRows) {
            List<List<Integer>> outerList = new LinkedList<>();
            if(numRows > 0){
                List<Integer> innerList = new LinkedList<>();
                innerList.add(1);
                outerList.add(innerList);
                List<Integer> prev = innerList;
                for(int i=1; i<numRows; i++){
                    innerList = new LinkedList<>();
                    innerList.add(1);
                    for(int j=1; j<=i-1; j++){
                        innerList.add(prev.get(j) + prev.get(j-1));
                    }   
                    innerList.add(1);
                    outerList.add(innerList);
                    prev = innerList;
                }
            }
            return outerList;
        }
    }

Log in to reply
 

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