2 Java solutions, dp


  • 0
    M

    Iteration solution:

        public int numTrees_iteration(int n) {
            if(n<=2) return n;
            int[] dp = new int[n+1];
            dp[0] = dp[1] = 1;
            dp[2] = 2;
            for(int i=3; i<=n; i++){
                for(int j=1; j<=i; j++){
                    dp[i] += dp[j-1]*dp[i-j];
                }
            }
            return dp[n];
        }
    

    Recursion solution:

        public int numTrees_recursion(int n) {
            if(n<=2) return n;
            int[] dp = new int[n+1];
            dp[0] = dp[1] = 1;
            dp[2] = 2;
            recursion(n, dp);
            return dp[n];
        }
        private int recursion(int n, int[] dp){
            if(dp[n]>0) return dp[n];
            for(int i=1; i<=n; i++){
                dp[n] += recursion(i-1, dp)*recursion(n-i, dp);
            }
            return dp[n];
        }
    

Log in to reply
 

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