Unique Binary Search Trees

当数组为 1,2,3,4,.. i,.. n时,基于以下原则的BST建树具有唯一性:

以i为根节点的树,其左子树由[0, i-1]构成, 其右子树由[i+1, n]构成。

再由递归便可得:

public static int numTrees(int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int[] myarray = new int[n+1];
        return getNumTree(n,myarray);
    }


public static int getNumTree(int n, int[] myarray){ if(myarray[n] != 0) return myarray[n]; if(n == 0) { myarray[0] = 1; return 1; } if(n == 1) { myarray[1] = 1; return 1; } int count = 0; for(int i = 0; i < n; i++) { count += getNumTree(i,myarray) * getNumTree(n-1-i,myarray); } myarray[n] = count; return myarray[n]; }
原文地址:https://www.cnblogs.com/jasonC/p/3404751.html