DFS初练

Description

作为DFS的基础题,我们要求对于1~N按字典序输出所有的排列情况。

Input

N(1 <= N <= 9)
注:测试数据包含多组

Output

输出对应的字典序全排列,数之间以空格隔开,每个排列最后一个数后换行。
每个数据处理完后空一行

Sample Input Copy

2
3

Sample Output Copy

1 2
2 1

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

AC代码

#include<bits/stdc++.h>
using namespace std;
#define ios ios::sync_with_stdio(false); cin.tie(NULL);
const int N = 10;
int cnt[N];//存储准备输出的数
bool vis[N];//标记是否使用过该数
int t;//判断存储了几个数
void dfs(int n)
{
    if(t==n)
    {
        for(int i=0; i<t; i++)
        {
            cout<<cnt[i];
            if(i!=t)
                cout<<' ';
        }
        cout<<'\n';
        return ;
    }
    for(int i=1; i<=n; i++)
    {
        if(!vis[i])
        {
            vis[i] = true;
            cnt[t] = i;
            t++;
            dfs(n);
            vis[i] = false;
            t--;
        }
    }

}

int main()
{
    int n;
    while(cin>>n)
    {
        dfs(n);
        cout<<'\n';
    }
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值