简单的dfs暴力枚举系列题

本文探讨了如何生成长度为n的01序列,确保序列中没有连续的两个零出现。通过深度优先搜索(DFS)算法,实现了序列的生成与存储。最后,使用排序算法对所有可能的序列进行排序并打印,提供了一段AC代码作为实现参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是题目链接:
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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值