全排列 ← dfs 及 next_permutation() 两种方法实现

算法代码一:dfs
dfs算法常表现为复杂的递归函数形式,因此掌握递归是理解dfs算法的基础。
dfs算法的模板如下:

void dfs(int step) {
    判断边界 {
        输出解
    }

    尝试每一种可能 {
        满足check条件{
            标记
            继续下一步:dfs(step+1)
            恢复初始状态(回溯的时候要用到)
        }
    }
}

 全排列的 dfs 实现的代码如下所示:

#include <bits/stdc++.h>
using namespace std;

const int maxn=10;
int a[maxn];
int book[maxn];
int n;

void dfs(int step){
	if(step==n+1){
		for(int i=1;i<=n;i++){
			cout<<a[i]<<" ";
		}
		cout<<endl;
		return;
	}
		
	for(int i=1;i<=n;i++){
		if(book[i]==0){
			a[step]=i;
			book[i]=1;
			dfs(step+1);
			book[i]=0;
		}		
	}
	return;
}

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


【算法代码二:next_permutation()】
在使用 next_permutation() 的时候,初始序列一般是一个字典序最小的序列。
如果不是,可以用 sort() 排序,得到最小序列,然后再使用 next_permutation()。
全排列的 next_permutation() 实现的代码如下所示:

#include <bits/stdc++.h>
using namespace std;

const int maxn=100;
int a[maxn];
int n;

int main() {
    cin>>n;
    for(int i=1; i<=n; i++) a[i]=i;
    sort(a+1,a+1+n);
    do {
        for(int i=1; i<=n; i++) cout<<a[i]<<" ";
        cout<<endl;
    } while(next_permutation(a+1,a+1+n));

    return 0;
}

/*
in:
3

out:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
*/


【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/134226708
https://blog.csdn.net/hnjzsyjyj/article/details/134347639
https://blog.csdn.net/hnjzsyjyj/article/details/118613417
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值