排列型枚举(全排列)
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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了