Commented 1ms Java Solution


  • 0
    G

    I thought I'd include a graphic about how the indexing works, for people (like me) who have a hard time visualizing multi-dimensional indexing.

    public class Solution {
        
        /**
         * Given an integer, return that many rows of Pascal's Triangle.
         * 
         * A triangular [i][j] index is used here, as follows:
         *      [0]  [1]             [2]               [3]        ... [m] {j}
         * [0]   1
         * [1]   1    1
         * [2]   1    2               1
         * [3]   1    3               3                 1
         * ...
         * [n]   1 1+[n-1][1] [n-1][1]+[n-1][2] [n-1][2]+[n-1][3] ...  1
         * {i}
         * 
         * @param numRows
         * @return 
         */
        public List<List<Integer>> generate(int numRows) {
            List<List<Integer>> ans = new ArrayList<>();
            
            // Handle bad numRows input
            if (numRows <= 0) return ans;
            ans.add(new ArrayList<>(Arrays.asList(1)));
            
            // Handle just wanting the first row
            if (numRows == 1) return ans;
            ans.add(new ArrayList<>(Arrays.asList(1, 1)));
            int i = 2;
            
            // Use the above row to fill the current row, then add to ans
            while (i < numRows) {
                ArrayList<Integer> row = new ArrayList<>();
                row.add(1);
                for (int j = 1; j < i; j++) {
                    row.add(ans.get(i-1).get(j-1) + ans.get(i-1).get(j));
                }
                row.add(1);
                ans.add(row);
                i++;
            }
            return ans;
        }
    }
    

Log in to reply
 

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