(1)描述:编写程序,产生由1,2,3这3个数字符号所构成、长度为n的字符串,并且在字符串中对于任何一个子串而言,都不会有相邻的、完全相同的子串;
(2)输入:字符串长度n;
(3)输出:无相邻重复子串的所有字符串,每个字符串换行输出。
思路是“三进制”,此代码的n最大到9。
- #include <iostream>
-
#include <cmath>
-
-
using namespace std;
-
-
void fun2 (int & p,int & n);
-
-
void fun1(int & p, int & n){
-
-
p=int(p/10)+1;//进位操作
-
n++;
-
fun2(p,n);
-
}
-
-
void fun2(int & p, int & n){
-
-
if(p%10==4)fun1(p,n);//判断前一位的数字是否需要进位
-
else{
-
n--;
-
p=p*int(pow(double(10),n)); //返回进位后得到的整数值(120,1300等)
-
}
-
-
}
-
-
void if_replicate(int &p){
-
-
int tmp1,tmp2,tmp3,label(1);//tmp1,tmp2用于判断相邻的是否有重复,tmp3暂存p值,label标签
-
tmp3=p;
-
while(tmp3>10){
-
tmp1=tmp3%10;
-
tmp3=int(tmp3/10);
-
tmp2=tmp3%10;
-
if(tmp1==tmp2){label=0;break;}
- }
- if(label){
int count[33]={0};
int list[10]={0};
int i(0),j(0);
tmp3=p;
while(i++<(10)){
list[i]=int(tmp3%100);
count[list[i]]++;
tmp3=int(tmp3/10);
}
while(j++<10){
if(list[j]!=0&&count[list[j]]>=2){label=0;break;}
}
} -
if(label)
-
cout<<p<<endl;
-
}
-
-
void output(int num){
-
-
int k(1),p(0),n(0);
-
k=num;
-
-
while(num--)p+=int(pow(double(10),num)); //最开始的数字,1111,111,等
-
-
if_replicate(p);
-
-
while(p<int(pow(double(10),k))){
-
p++;
-
-
if(p%10==4){//是否需要进位
-
n=1;
-
fun1(p,n);
-
while(n--)p+=int(pow(double(10),n));//尾数赋值,如113-->121,133-->211等
-
n=1;}
-
if_replicate(p);
-
}
-
}
-
-
int main()
-
{
-
int num;
-
cout<<"Input a number: ";
-
cin>>num;
-
output(num);
-
return 0;
- }