终于到了我最熟悉的回溯法了
#include<iostream>
using namespace std;
int sum=0;//记录答案总个数。
const int n = 7;//第一行一共有多少个符号,n>=2
int triangular_matrix[n][n]{0};//存储符号(+用1表示,-用-1表示)
void solve(int floor,int Count);
void dispose(int index,int Count);//处理第一行
int main()
{
int Count = 0;
dispose(0, Count);
cout << sum << endl;
return 0;
}
void solve(int floor,int Count)
{
if (floor == n - 1)
{
if (Count == 0)//+与-个数相等
++sum;
}
else if (floor < n - 1)
{
int bound = n - floor;
for (int i = 0; i < bound-1; i++)
{
if ((triangular_matrix[floor][i] == 1) && (triangular_matrix[floor][i + 1] == 1)
|| (triangular_matrix[floor][i] == -1) && (triangular_matrix[floor][i + 1] == -1))
//相邻的两个同号
{
triangular_matrix[floor + 1][i] = 1;
++Count;
}
else//相邻的两个不同号
{
triangular_matrix[floor + 1][i] = -1;
--Count;
}
}
solve(floor + 1, Count);
}
return;
}
void dispose(int index,int Count)
{
if (index == n)
solve(0, Count);
else
{
triangular_matrix[0][index] = 1;
dispose(index + 1, Count+1);
triangular_matrix[0][index] = -1;
dispose(index + 1, Count-1);
}
return;
}