1ms java


  • 0
    A
        public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> pascal = new ArrayList<>(numRows);
        for (int i=1; i<=numRows; i++) {
            List<Integer> array = new ArrayList<>(i);
            for (int j=1; j<=i; j++) {
                if (j == 1 || j == i) array.add(1);
                else {
                    array.add(
                        pascal.get(i-1-1).get(j-1-1) + 
                        pascal.get(i-1-1).get(j-1) 
                    );
                }
            }
            pascal.add(array);
        }
        return pascal;
    }

  • 0
    C
    This post is deleted!

  • 0
    C

    @codinglol said in 1ms java:

    My solution is almost same with you, but it takes 2ms.

        public List<List<Integer>> generate(int numRows) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
    
            for (int i = 0; i < numRows; ++i) {
                List<Integer> row = new ArrayList<Integer>();
                for (int j = 0; j <= i; ++j) {
                    if (j == 0 || j == i) {
                        row.add(1);
                    }
                    else {
                        row.add(result.get(i - 1).get(j -1) + result.get(i - 1).get(j));
                    }
                }
                result.add(row);
            }
    
            return result;
        }
    

    well, I know why... I think the extra 1ms is because of the allocation of ArrayList.


Log in to reply
 

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