然後也有遞推出來的解,設dp[n][2],n表示還有n個子節點未分配,2表示0為最多分配n - 1個點,1為最多分配n個點,這樣能保證子樹都至少有兩個節點,這樣就是總情況了,直接用記憶化搜下去即可
代碼:
公式解:
#include#include int n; long long Catalan[30], SuperCatalan[30]; int main() { Catalan[1] = Catalan[2] = 1; for (int i = 3; i <= 26; i++) { Catalan[i] = Catalan[i - 1] * (4 * i - 6) / i; } SuperCatalan[1] = SuperCatalan[2] = 1; for (int i = 3; i <= 26; i++) { SuperCatalan[i] = (3 * (2 * i - 3) * SuperCatalan[i - 1] - (i - 3) * SuperCatalan[i - 2]) / i; } while (~scanf("%d", &n)) { printf("%lld\n", SuperCatalan[n] - Catalan[n]); } return 0; }
#include#include int n; long long Catalan[30], dp[30][2]; long long dfs(int n, int flag) { long long &ans = dp[n][flag]; if (~ans) return ans; if (n <= 1) return ans = 1; ans = 0; for (int i = 1; i < n + flag; i++) ans += dfs(i, 0) * dfs(n - i, 1); return ans; } int main() { Catalan[1] = Catalan[2] = 1; for (int i = 3; i <= 26; i++) { Catalan[i] = Catalan[i - 1] * (4 * i - 6) / i; } while (~scanf("%d", &n)) { memset(dp, -1, sizeof(dp)); printf("%lld\n", dfs(n, 0) - Catalan[n]); } return 0; }