188ms Java Recursive Solution


  • 1
    T
    public List<List<Integer>> generate(int numRows) {
        return generateHelper(new ArrayList<List<Integer>>(), numRows);
    }
    
    private List<List<Integer>> generateHelper(List<List<Integer>> tri, int numRows) {
        if (numRows == 0) {
            // base case
            return tri;
        }
        
        List<Integer> newList = new ArrayList<Integer>();
        newList.add(1);
        if (tri.size() != 0) {
            // compute pascal triangle
            List<Integer> lastList = tri.get(tri.size() - 1);
            for (int i = 0; i < lastList.size() - 1; i++) {
                int curr = lastList.get(i);
                int next = lastList.get(i + 1);
                newList.add(curr + next);
            }
            newList.add(1);
        }
        tri.add(newList);
        return generateHelper(tri, numRows - 1);
    }

Log in to reply
 

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