My JAVA solution 1ms


  • 0
    S

    The basic idea is to add the previous 2 indices from the previous row.
    For example :
    [1]
    [1 1]
    [1 2 1]
    [1 3 3 1]
    To get 2, in the third row, we have to add up 1 + 1 from the previous row.

        public List<List<Integer>> generate(int numRows) {
            List<List<Integer>> arr = new ArrayList<List<Integer>>();
            if(numRows == 0)
                return arr;
            arr.add(new ArrayList<>());
            arr.get(0).add(1);
            if(numRows == 1)
                return arr;
            arr.add(new ArrayList<>());
            arr.get(1).add(1);
            arr.get(1).add(1);
            if(numRows == 2)
                return arr;
            for(int i = 2; i < numRows; i++) {
                arr.add(new ArrayList<>());
                arr.get(i).add(1);
                for(int j = 0; j < arr.get(i-1).size() - 1; j++) {
                    int sum = arr.get(i-1).get(j) + arr.get(i-1).get(j+1);
                    arr.get(i).add(sum);
                }
                arr.get(i).add(1);
            }
            return arr;
        }
    }

Log in to reply
 

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