My java solution


  • 0
    P
        private static List<List<Integer>> generate(int numRows) {
            List<List<Integer>> triangle = new ArrayList<>();
            // check if empty
            if (numRows <= 0){
                return  triangle;
            }
            // first row here
            List<Integer> first = new ArrayList<>(1);
            first.add(1);
            triangle.add(0,first);
            // start from the second row
            for (int i = 1; i < numRows; i++){
                List<Integer> row = new ArrayList<>(i + 1);
                // put first and last digit as 1
                row.add(0,1);
                row.add(1);
                // length of previous row
                int length = triangle.get(i - 1).size();
                // no need to add anything else for second row
                if (length > 1) {
                    int index = 1;
                    int j = 0;
                    // get value from previous row and add up get new value for current row
                    while (index <= i - 1) {
                        int temp = triangle.get(i - 1).get(j) + triangle.get(i - 1).get(j + 1);
                        row.add(index, temp);
                        index++;
                        j++;
                    }
                }
                // insert
                triangle.add(i, row);
            }
            return  triangle;
    }
    
    

Log in to reply
 

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