洛谷——P1044 栈

第一种方法就是搜索,必然超时…

#include<iostream>
#include<cstring>
using namespace std;
long long ans = 0;
int n;
void DFS(int in, int rout) {
	if (rout == 0) {
		ans++;
		return;
	}
	if (in == 0)
		DFS(in + 1, rout - 1);
	else {
		DFS(in - 1, rout);
		DFS(in + 1, rout - 1);
	}
}
int main()
{
	cin >> n;
	DFS(0, n);
	cout << ans;
	return 0;
}

当然,可以优化,我们采用记忆化搜索。dp[i][j]表示的是在栈内有i个元素,操作数有j个元素时的最大方案书。

#include<iostream>
#include<cstring>
using namespace std;
long long ans = 0;
int n;
long long dp[20][20];
long long DFS(int in, int rout) {
	if (rout == 0)
		return 1;
	if (dp[in][rout])
		return dp[in][rout];
		dp[in][rout]+= DFS(in + 1, rout - 1);
		if (in > 0)
			dp[in][rout] += DFS(in - 1, rout);
		return dp[in][rout];
}
int main()
{
	dp[0][0] = { 0 };
	cin >> n;
	cout << DFS(0, n);
	return 0;
}

再写成动态规划的形式

#include<iostream>
#include<cstring>
using namespace std;
long long dp[20][20];
int n;
int main()
{
 cin >> n;
 for (int rout = 0; rout <= n; rout++) {
  for (int in = 0; in <= n; in++) {
   if (rout == 0)
    dp[in][rout] = 1;
   else {
    dp[in][rout] += dp[in + 1][rout - 1];
    if (in > 0)
     dp[in][rout] += dp[in - 1][rout];
   }
  }
 }
 cout << dp[0][n];
 return 0;
}

百度一下卡特兰数
(溜~

发布了14 篇原创文章 · 获赞 3 · 访问量 149

猜你喜欢

转载自blog.csdn.net/IMDASHUAI/article/details/104771289