算法题(173):枚举排列

📅 2026/7/15 2:44:38 👁️ 阅读次数 📝 编程学习
算法题(173):枚举排列

审题:
本题需要我们找出所有排列方式并按照字典序排序输出

思路:
方法一:dfs深度优先搜索

由于最后还需要我们按照字典序输出,且无法事先确定需要的for循环层数,所以我们这里不能采用简单的for循环解决

决策树:

在选取的时候我们依次选取前面没有选过的数插入即可,最后选取满k就输出答案

解题:

#include<iostream> #include<vector> using namespace std; int n, k; vector<int> path; bool judge[10]; void dfs() { if (path.size() == k) { for (auto e : path) cout << e << " "; cout << endl; return; } for (int i = 1; i <= n; i++) { //数据选取 if (judge[i] == true) continue;//选择过该数,跳过 path.push_back(i); judge[i] = true; dfs(); //数据回退 path.pop_back(); judge[i] = false; } } int main() { cin >> n >> k; dfs(); return 0; }

注意:

1.使用bool数组来判断对应数据是否选取过,为false就是没选过,true就是选过

2.在选择完成和回溯的时候要注意将数据选取状态调整回来

B3623 枚举排列(递归实现排列型枚举) - 洛谷