Easy solution using recursion


  • 0
    class Solution {
    public:
        Solution(){
            save.push_back(1);
            save.push_back(1);
            save.push_back(2);
            save.push_back(5);
        }
        int numTrees(int n) {
            if(n<save.size())
                return save[n];//store the temp result to save time
            int total=0;
            for(int i=1;i<=n;++i)
                total+=numTrees(i-1)*numTrees(n-i);//left*right
            save.push_back(total);
            return total;
        }
    private:
        vector<int>save;
    };

Log in to reply
 

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