两种算法,思想都是左括号始终大于等于右括号,当左括号等于右括号的时候且等于N的时候。记录为1
#include
#include
#include
#include
#include
#include
#include
using namespace std;
void display(int x, int y)
{
cout << x << " " << y << endl;
}
int num = 0;
string str = “”;
vector strvec;
void kuohaosuanfa(int l,int r,int n)
{
if (l < n)
{
str = str + “(”;
kuohaosuanfa(l + 1, r, n);
str.pop_back();
}
if (r < l && r < n)
{
str = str + “)”;
kuohaosuanfa(l, r+1, n);
str.pop_back();
}
if (l == r && l== n)
{
strvec.push_back(str);
num++;
}
}
int main()
{
auto f = std::bind(display, 555, std::placeholders::_1);
auto f1 = std::bind(display, std::placeholders::_1, 777);
f(10);
f1(666);
kuohaosuanfa(0, 0, 4);
cout << num << endl;
for (auto x : strvec)
{
cout << x << endl;
}
/第二种算法/
const int N = 5;
int dp[N + 5][N + 5];
memset(dp, 0, sizeof(dp));
dp[1][1] = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
if (i == 1 && j == 1) continue;
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
printf("%d\n", dp[5][5]);
system(“pause”);
return 0;
}
N个括号有多少种合法的组合
最新推荐文章于 2021-10-24 17:16:26 发布