Simple Easy to understand java solution


  • 0
    A
    public class Solution {
        public List<List<Integer>> generate(int numRows) {
            List<List<Integer>> result = new ArrayList<List<Integer>>(numRows);
            ArrayList<Integer> previous = null;
            ArrayList<Integer> current = null;
        
            for (int i = 0; i < numRows; i++) {
                // Except 1st and last element, all other elements of a row in Pascal's 
                // triangle is equal to the sum of current indexe's element and the 
                // predecessor index's element.
                current = new ArrayList<Integer>(i+1);
                current.add(1);
                if (previous != null) {
                    for (int j = 1; j < i; j++) {
                        current.add(previous.get(j-1) + previous.get(j));
                    }
                    current.add(1);
                }
                result.add(current);
                previous = current;
            }
        
            return result;
        }
    }

Log in to reply
 

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