根据公式计算卡特兰数,始终出现越界,自己无法解决
#include <iostream> using namespace std; long long Catalan(int num) { long long result = 1; for (int i = 1; i <= num; i++) result *= (i + num); for (int i = 1; i <= num; i++) result /= i; result /= (num + 1); return (long long)result; } int main() { int num; int i = 1; while (cin >> num && num != -1) { printf("%d %d %I64d\n", i++, num, 2 * Catalan(num)); } }
根据递推公式
动态规划
#include <iostream> using namespace std; long long dp[36][36]; int main() { int num; int i = 1; for (int i = 0; i <= 35; i++) dp[i][0] = 1; for (int i = 1; i <= 35; i++) { for (int j = 0; j <= i; j++) { if (i == j) dp[i][j] = dp[i][j - 1]; else dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } while (cin >> num && num != -1) { printf("%d %d %I64d\n", i++, num, 2 * dp[num][num]); } }