【CODE】卡塔兰数列应用——二叉搜索树的个数

96. Unique Binary Search Trees

Medium

254295Add to ListShare

Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?

Example:

Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
class Solution {
public:
    int numTrees(int n) {
        if(n==1) return 1;
        if(n==2) return 2;
        vector dp(n+1);
        dp[0]=1;dp[1]=1;dp[2]=2;
        for(int i=3;i<=n;i++){
            for(int j=0;j

95. Unique Binary Search Trees II

Medium

1738139Add to ListShare

Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.

Example:

Input: 3
Output:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector helper(int a,int b,vector > > memo){
        if(b res;
        for(int i=a;i<=b;i++){
            vector left=helper(a,i-1,memo);
            vector right=helper(i+1,b,memo);
            for(int j=0;jval=i;
                    tmp->left=left[j];
                    tmp->right=right[k];
                    res.push_back(tmp);
                }
            }
        }
        memo[a-1][b-1]=res;
        return res;
    }
    vector generateTrees(int n) {
        if(n==0) return {};
        vector > > memo(n,vector>(n));
        return helper(1,n,memo);
    }
};

241. Different Ways to Add Parentheses

Medium

134066Add to ListShare

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +- and *.

Example 1:

Input: "2-1-1"
Output: [0, 2]
Explanation: 
((2-1)-1) = 0 
(2-(1-1)) = 2

Example 2:

Input: "2*3-4*5"
Output: [-34, -14, -10, -10, 10]
Explanation: 
(2*(3-(4*5))) = -34 
((2*3)-(4*5)) = -14 
((2*(3-4))*5) = -10 
(2*((3-4)*5)) = -10 
(((2*3)-4)*5) = 10
class Solution {
public:
    vector diffWaysToCompute(string input) {
        vector res;
        for(int i=0;i left=diffWaysToCompute(input.substr(0,i));
                vector right=diffWaysToCompute(input.substr(i+1));
                for(int j=0;j

 

你可能感兴趣的:(C/C++)