dfs全排序

该代码使用深度优先搜索(DFS)方法模拟了next_permutation的过程,对一个整数序列进行排列。当找到一个满足相邻元素严格升序的序列(即序列的下一个排列)时,将其输出。程序接收两个参数n和m,表示在1到n的数字中选取m个进行排列。
摘要由CSDN通过智能技术生成

模拟next_permutation

#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

int n, m;
const int N = 10;

int path[N];
bool st[N];

void dfs(int u)
{
    if (u == m)
    {
        int sum = 0;
        for(int i = 0; i < m; i ++ )
            if (path[i] < path[i + 1]) sum ++;
            
        if(sum == m - 1)
        {
            for(int i = 0; i < m; i ++ )
            printf("%d ", path[i]);
            puts("");
        }
        return;
    }
    
    for(int i = 1; i <=n; i ++ )
    {
        if(!st[i])
        {
            path[u] = i;
            st[i] = true;
            dfs(u + 1);
            st[i] = false;
        }
    }
}

int main()
{
    cin >> n >> m;
    
    dfs(0);
    
    return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值