这是题目链接:
http://39.107.118.220/problem.php?cid=1001&pid=9
大致意思就是01序列的长度为n不能有两个零相邻,求出所有可能情况,并按照从小到大打印出来,很简单直接dfs再加一个字符数组存结果以便排序。
AC代码:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int ans = 0;
int n;
int num[20];
string s[10000];
void dfs(int k,int step)
{
num[step] = k;
if(step == n)
{
ans++;
for(int i = 1;i <= n;i++)
{
s[ans] += (num[i] + '0');
}
//cout << s[ans] << endl;
return ;
}
if(k == 0)
{
dfs(1,step + 1);
}
else
{
dfs(1,step + 1);
dfs(0,step + 1);
}
}
bool cmp(string a,string b)
{
return a<b;
}
int main()
{
while(cin >> n)
{
for(int i = 0;i < 10000;i++) s[i] = "";
ans = 0;
dfs(0,1);
dfs(1,1);
sort(s + 1,s + ans + 1 ,cmp);
for(int i = 1;i <= ans;i++) cout << s[i] << endl;
}
}