题目描述
从三个元素[A,B,C]的集合中选取N元素生成一个个字符组成的序列,使得没有两个相邻的子序列(子序列长度=2)
输入格式
输入N
输出格式
求出满足条件的N个字符的所有序列的总数。
我们肯定会直接分三种情况填,最后填好时继续判断:
#include <iostream>
using namespace std;
int sum = 0;
char abc[4] = { ' ', 'A', 'B', 'C' };
string a;
int ds;
bool Same(string s) {
int len = s.length();
string pre = "\n";
for (int i = 0; i < len - 1; i++) {
if (pre == s.substr(i, 2))
return 1;
if (i != 0)
pre = s.substr(i - 1, 2);
}
return 0;
}
void Dfs(int nowd) {
if (nowd == ds) {
if (Same(a) == 0)
sum++;
return;
}
for (int i = 1; i <= 3; i++) {
a[nowd] = abc[i];
Dfs(nowd + 1);
}
}
int main() {
cin >> ds;
Dfs(0);
cout << sum;
}
但却是错的,调试时无缘发现a忽然变成了空串?!
就是它的赋值有问题,a刚开始并没有定义过长度,导致赋值发生错误,所以我们可以——
#include <iostream>
using namespace std;
int sum = 0;
char abc[4] = { ' ', 'A', 'B', 'C' };
string a;
int ds;
bool Same(string s) {
int len = s.length();
string pre;
for (int i = 1; i < len - 1; i++) {
if (pre == s.substr(i, 2))
return 1;
pre = s.substr(i - 1, 2);
}
return 0;
}
void Dfs(int nowd) {
if (nowd == ds) {
if (Same(a) == 0)
sum++;
return;
}
for (int i = 1; i <= 3; i++) {
a.push_back(abc[i]);
Dfs(nowd + 1);
a.erase(nowd, 1);
}
}
int main() {
cin >> ds;
Dfs(0);
cout << sum;
}