排列型枚举(全排列)

0.简介

在排列型枚举中,我们从给定的元素集合中选择出若干个元素的所有可能排列,这些排列考虑了元素的顺序.

1.代码模板

#include<bits/stdc++.h>
using namespace std;
int n;
int order[20];
bool chosen[20];

// x代表当前选择位 
void DFS(int x) {
	// 选满了
	if (x == n + 1) {
		for(int i = 1; i <= n; i++) {
			cout << order[i] << " ";
		}
		cout << endl;
		return; 
	}

	for(int i = 1; i <= n; i++) {
		if(chosen[i]) continue;
		else {
			// 选中当前的数, 进入下一层搜索 
			chosen[i] = true;
			order[x] = i;
			DFS(x + 1);
			// 不选中,进入下一次循环, 还在当前层 
			chosen[i] = false;
			order[x] = 0;
		}
	}

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

2.使用next_permutation

总是向着更大的字典序方向

#include<bits/stdc++.h>
using namespace std;
int n;
int order[20];
bool chosen[20];

string getStr(int n) {
	stringstream ss;
	for(int i = 1; i <= n; i++) {
		ss << i;
	}
	return ss.str();
}
int main() {
	cin >> n;
	string s = getStr(n);
	do {
		cout << s << '\n';
	} while(std::next_permutation(s.begin(), s.end()));
	return 0;
}
posted @   DawnTraveler  阅读(78)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示