題目連結

It’s basically cutting stick DP. For the given range, try using every possible value as the root, and then D&C

AC Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// :%s/^ \* //g
#ifdef LOCAL
#include <bits/stdc++.h>
using namespace std;

// define data structures here
#endif

static int __initialSetup = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}
();

class Solution
{
private:
    int dfs(int l, int r, vector<vector<int>> &dp) // [l, r)
    {
        if (r - l <= 1)
            return dp[l][r] = 1;
        if (dp[l][r] != 0)
            return dp[l][r];

        for (int i = l; i < r; i++) { // for every root
            dp[l][r] += dfs(l, i, dp) * dfs(i + 1, r, dp);
        }

        return dp[l][r];
    }

public:
    int numTrees(int n)
    {
        vector<vector<int>> dp(n + 2, vector<int>(n + 2, 0));

        return dfs(1, n + 1, dp);
    }
};

#ifdef LOCAL
int main()
{
    return 0;
}
#endif