Shorter solution in Java with a minor issue


  • 4
    P
    class UniqueBSTs {
     public int numTrees(int n){
        int sum = 0;
        if(n == 0) return 1;
        for(int i = 1; i <= n; i++)
           sum += numTress(n -i) * numTrees(i - 1);
      }
      return sum;
    }  
    

    The solution is accepted at time cost 205ms;
    One minor issue is when n = 0, then this solution would give 1. But actually 0 nodes should generate 0 trees.
    Or this issue is acceptable?


  • 0
    J

    it is acceptable, since 0 node forms a null tree. It is the base of the recursion.


  • 0
    H

    This solution is likely to get TLE.


Log in to reply
 

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